JavaScript

DOM Event Listener method in JavaScript

You can add the event listener to the HTML DOM elements with the help of the addEventListener() method. The addEventListener() method permits you to control the reaction for the corresponding event. The JavaScript is isolated from the HTML text when you utilize the addEventListener() method, making it easy to comprehend and enabling you to add event listeners even if you do not control the HTML Markup.

This write-up will discuss the DOM Event Listener method in JavaScript. We will explain the usage of the DOM Event Listener method for adding single and multiple handlers to the HTML elements. Moreover, examples related to Event Bubbling and Event capturing will also be demonstrated. So, let’s start!

DOM Event Listener method in JavaScript

As a JavaScript programmer, you can utilize the DOM addEventListener() method for adding an event listener on any HTM object such as the window objects, HTML elements, HTML document or xmlHttpRequest object.

There exists another “on” JavaScript property that is used for the same purpose; however, it is not much useful as compared to the addEventListener() method because the DOM addEventListener() method permits you for adding multiple event listeners on a window object or HTML element.

Syntax of addEventListener() method

object.addEventListener(event, function, useCapture);

Here, the first parameter, “event” is added to specify the event for which you want to add the event handler; the second parameter, “function” invokes the function that will be executed when the specified event occurs. The third parameter is optional; where you have to add either“event capturing” or “event bubbling”.

Example 1: Using DOM Evener Listener method for adding an Event Handler in JavaScript

This example will show you the procedure of adding a DOM Event Listener method for the mouse “click” event in JavaScript. Firstly, we will add a heading with the <h2> tag, a paragraph with the <p> tag, and a button by using the <button> tag:

<!DOCTYPE html>
<html>
<body>

<h2> DOM Event Listener Method In JavaScript</h2>

<p>This JavaScript program utilized addEventListener() method</p>

We have also added an id “button1” for our “Click me” button:

<button id="button1">Click me</button>

<p id="p1"></p>

The getElementById method will be invoked to find and get the button having “button1” id. After that, the “addEventListener()” method will add a “click” event which will trigger the “displayDate()” method:

<script>
document.getElementById("button1").addEventListener("click", displayDate);

According to the added code, when the user clicks the mentioned button, the current date will be displayed as output:

function displayDate() {
  document.getElementById("p1").innerHTML = Date();
}
</script>

</body>
</html>

Execute the above-given program in your favorite code editor or any online coding sandbox; however, we will utilize the JSBin for this purpose:

After getting the output, click on the “Click me” button to check out the current time and date:

Example 2: Using DOM Evener Listener method for adding Multiple Event Handlers in JavaScript

JavaScript also offers the functionality to add multiple event handlers for the same object. To demonstrate its procedure, we have written the following JavaScript program with a heading, paragraph, and a button having “button1” id. Note that we will add multiple event handlers for the “button” HTML element:

<!DOCTYPE html
<html>
<body>

<h2> Add an Event Handler in JavaScript</h2>

<p>This JavaScript program utilized addEventListener() method</p>

<button id="button1">Click me</button>

In the next step, we will an “a” object that will find and get the button with “button1” id through invoking the document.getElementById() method:

<script>
var a = document.getElementById("button1");

Then, we will add two event listeners for the button “click” event; the first addEventListener() method will invoke the “firstFunction”, whereas, the second addEventListener() method will call the “secondFunction”:

a.addEventListener("click", firstFunction);
a.addEventListener("click", secondFunction);

function firstFunction() {
  alert ("this is linuxhint.com");
}

function secondFunction() {
  alert ("second function is executed");
}
</script>

</body>
</html>

Hit the “Click me” button, and you get two alerts on your browser, one after another:

Example 3: Using DOM Event Listener Method for adding Event Handler to the window Object in JavaScript

In the following example, we are adding the addEventListener() method to the “window” object. The added addEventListener() method will be triggered when a user performs the “mousedown” action:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method on the window object.</p>

We will also pass an “event” object to the addEventListener() method. The “event” object comprises all of the information related to the mousedown event:

<script>
window.addEventListener("mousedown",function(event){
alert("Event is mousedown");
console.log(event);
});
</script>

</body>
</html>

Execution of the above-given JavaScript program will show the following output:

Now, press the “left” mouse button over the selected element, and you will see the following alert:

Event Bubbling in JavaScript

In JavaScript, Event Bubbling is an event that bubbles up from the target or the deepest elements to its parents, then it follows the bottom to top approach and moves the control flow to its ancestors. Event bubbling is considered as default event flow method in all modern browsers.

Example: Event Bubbling in JavaScript

In the following example, we have added a title with the <title> tag, a div element with the id “parentElement” and its nested child button element having the id “childElement”:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Event Bubbling</title>
</head>
<body>
  <div id="parentElement">
    <button id="childElement">Child</button>
  </div>

After assigning the created HTML elements by using the “document.querySelector()” method, we will add an event listener to both div “parentElement” and its nested “childElement” button. The function passed in the “addEventListener()” will display the added string in the “console.log()” method:

  <script>
    var parent = document.querySelector('#parentElement');
      parent.addEventListener('click', function(){
        console.log("Clicked Parent");
      });

    var child = document.querySelector('#childElement');
      child.addEventListener('click', function(){
        console.log("Clicked Child");
      });
  </script>
</body>
</html>

Now, we will click on the “Child” button, which can be seen in the following output:

By clicking the “Child” button, the passed “function()” in the addEventListener() method will be executed. Then, the “onclick()” method of the “div” element will be invoked. This all happens because of the “Event Bubbling”:

In the above-given example, when we have clicked the “Child” button, the “click” event is passed from the button having id “childElement” and event flow control moves to the “document” in the following order:

Event capturing in JavaScript

The process in which an event is captured when its flow of control moves from the top element to the target or outermost element is known as Event capturing. Although modern browsers do not have the capability to enable event capturing by default, you can perform this operation through JavaScript code.

Example: Event Capturing in JavaScript

In our JavaScript program, first of all, we will add a title and a “div” element having id “parentElement” and its child element with “childElement” id:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Event Capturing</title>
</head>
<body>
  <div id="parentElement">
    <button id="childElement">Child</button>
  </div>

Next, we will invoke the “document.querySelector()” method to get the parent and child element:

<script>
    var parent = document.querySelector('#parentElement');
    var child = document.querySelector('#childElement');

After doing so, event listeners are added to both of our HTML elements by using the “addEventListener()” method. To enable the “Event Capturing” in the parent div element, we will also set the third parameter’s value of the addEventListener() method to “true”. This action will force the JavaScript interpreter to firstly execute the parent element event and then move the vent flow control to the event target:

parent.addEventListener('click', function(){
      console.log("Clicked Parent ");
    },true);

    child.addEventListener('click', function(){
      console.log("Clicked Child");
    });
  </script>
</body>
</html>

The following “Child” button will first invoke the event added to the parent element. After that, it will execute the event attached to the event target:

In the above-given example, when we have clicked the “Child” button, the “click” event is passed from the parent element which is “document,” to the specified event target “childElement” button:

Conclusion

Using the DOM addEventListener() method, you can add an event listener to the window object and HTML elements. Without overwriting the existing event handlers, the addEventListener() JavaScript method assigns an event handler to the specific object. Also, a single window object can have multiple event handlers as well. This write-up discussed the DOM Event Listener method in JavaScript. We also explained the usage of the DOM Event Listener method for adding single and multiple handlers to the HTML elements. Moreover, examples related to Event Bubbling and Event capturing are also demonstrated.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.