Event handling in JavaScript. Code examples

Event handling in JavaScript. Code examples

Tested: ES6

For user interaction, JavaScript defines an event mechanism. For example, when the user clicks a button, the button click event is fired. In JavaScript code, we can determine the occurrence of an event and somehow handle it.

JavaScript has the following types of events:

  • Mouse events – (cursor movement, mouse click, etc.)
  • Element lifecycle events – e.g. web page load event
  • Form events – pressing a button on a form, selecting an element in a drop-down list, etc.
  • Events Raised When DOM Elements Change
  • Events Raised When Errors Occur

The function that occurs when an event is triggered is called an “event handler

Passing parameters to the event handler

You can pass parameters to the handler. For example, we can pass the current object on which the event occurs:

Example:

<a href="/" onclick="return handler(this)">Home</a>

in JS:

function handler(obj){
    alert(obj.href);
    return false;
}

The this keyword points to the current object of the link being clicked. And in the handler code, we can get this object and access its properties, for example, the href property.

Clicking on the link should result in a redirect. But by returning false from the handler, we can stop the standard way of handling the event, and there will be no redirection.

But by returning false from the handler, we can stop the standard way of handling the event, and there will be no redirection. If it returns true, then the event is processed in the standard way.

In addition to the event source element itself, we can pass the event object to the handler. This object is not defined by the developer, it is just an argument to the handler function that stores all the information about the event.

<head>
    <meta charset="utf-8" />
    <style>
    #rect{
        width:50px;
        height:50px;
        background-color:blue;
    }
    </style>
</head>
<body>
<div id="rect" onclick="handler(event)"></div>
<script>
function handler(e){
     
    alert(e.type); //get event type
}
</script>
</body>
[html]

<h2>Event Handlers</h2>

Our event handlers are defined in the element code using attributes:

[js]
<div id="rect" onclick="handler(event)"></div>
[/js]

This option has a lot of disadvantages:

<ol>
<li>
    html code is mixed with javascript code
</li>
<li>
    Event handlers can only be set for elements already created on the web page.
</li>
<li>
    Only one handler can be attached to an element for one event
</li>
<li>
    You can't remove a handler without changing the code
</li>
</ol>

Let's rewrite our example using event handler properties:


[html]
<head>
<title>Test</title>
</head>
<body>
<div id="elem"></div>
<script>
function handler(e){
     
    alert(e.type);
}
document.getElementById("elem").onclick = handler;
</script>
</body>

As a result, we just need to take the onclick property and assign it a function used as a handler. Due to this, the html code is separated from the JavaScript code.

It is also worth noting that the browser automatically passes an Event object to the event handler, which stores all information about the event.

Therefore, we can also receive this object in the handler function as a parameter.

Event Listeners

Another way to set up event handlers is to use listeners. To work with event listeners, JavaScript has an EventTarget object that defines methods addEventListener() (to add a listener) and removeEventListener() to remove a listener. And since HTML DOM elements are also EventTarget objects, they also have these methods. In fact, listeners represent the same functions of handlers.

The addEventListener() method takes two parameters: the name of the event without the on prefix, and the function of the event handler for this event:

var elem = document.getElementById("elem");
 
 elem.addEventListener("click", function (e) {
     alert(e.type);
 });

// you can just pass the name of the function
 elem.addEventListener("click", dofunction)

Removing a listener:

elem.removeEventListener("click", dofunction);

The advantage of using listeners is that we can set several functions for one event:

var elem = document.getElementById("elem");

elem.addEventListener("click", handlerOne);

elem.addEventListener("click", handlerTwo);

Event Object

As we said above, when processing an event, the browser automatically passes the Event object as a parameter to the handler function. This object stores all information about the event. With the help of its properties, we can get this information:

  • bubbles – returns true if the event is an upstream event. For example, if an event occurred on a nested element, then it can be handled on the parent element.
  • cancelable – returns true if it is possible to cancel the standard event handling
  • currentTarget – defines the element to which the event handler is attached
  • defaultPrevented – returns true if the preventDefault() method was called on the Event object
  • eventPhase – defines the stage of event processing
  • target – points to the element on which the event was fired
  • timeStamp – stores the time the event occurred
  • type – indicates the name of the event

Example:

function handler(event){
     
     console.log("Type: " + event.type);
      
     console.log(event.target);
 }

 var elem = document.getElementById("elem");
 elem.addEventListener("click", handler);

And in this case, the target property is an element, so we can manipulate it like any other nodes and DOM elements. For example, let’s change the background color:

function handler(e){
     e.target.style.backgroundColor = "red";
 }

Stop event execution

With the preventDefault() method of the Event object, we can stop the event from executing further.

For example, let’s disable clicking on a link after 12:00:

<a href="http://google.com" id="link">Search</a>
function linkHandler(e){
     
    var date = new Date();
    var hour = date.getHours();
    
	if(hour>12){
         
        e.preventDefault();
        document.write("After 12 the transition is prohibited");
    }
}
var link = document.getElementById("link");

link.addEventListener("click", linkHandler);

Event propagation

When we click on any element on the page and a click event is generated, that event can propagate from element to element. For example, if we click on a div block, then we also click on the body element in which the div block is located. That is, the event propagates.

There are several forms of event propagation:

Bubbling – the event propagates up the DOM tree from child nodes to parent nodes.

Capturing – the event propagates down the DOM tree from parent to child nodes until it reaches the element on which the event occurred.

Bubbling Events

Consider bubbling events that propagate up the DOM tree. Let’s say we have the following web page:

<head>
    <style>
    #blueRect{
        width:100px;
        height:100px;
        background-color:blue;
    }
    #redRect{
        width:50px;
        height:50px;
        background-color:red;
    }
    </style>
</head>
<body>
<div id="blueRect">
    <div id="redRect"></div>
</div>
 
<script>
var redRect = document.getElementById("redRect");
redRect.addEventListener("click", function(){
    console.log("On redRect");
});
 
var blueRect = document.getElementById("blueRect");
blueRect.addEventListener("click", function(){
    console.log("On blueRect");
});
 
document.body.addEventListener("click", function(){
    console.log("On body");
});
</script>
</body>

Needless to say, this behavior is not always desirable. And in this case, we can stop the propagation of the event using the stopPropagation() method of the Event object:

var redRect = document.getElementById("redRect");
redRect.addEventListener("click", function(e){
    console.log("On redRect");
    e.stopPropagation();
});

As a result of clicking, the event will be processed only by the handler for redRect.

Capturing Events

Events can also be downstream (capturing). To use them, the addEventListener() method passes a boolean true or false as the third optional parameter to indicate whether the event will descend.

By default, all events are ascending.

Let’s take the same web page, just change its javascript code:

var redRect = document.getElementById("redRect");
redRect.addEventListener("click", function(){
    console.log("On redRect");
}, true);
 
var blueRect = document.getElementById("blueRect");
blueRect.addEventListener("click", function(){
    console.log("On blueRect");
}, true);
 
document.body.addEventListener("click", function(){
    console.log("On  body");
}, true);

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation