Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Understanding Events and Event Handlers
3.
What is addEventListener () in JavaScript?
3.1.
Syntax of addEventListener() in JavaScript
3.2.
Parameters of addEventListener() in JavaScript
4.
Event Capturing
4.1.
Event Capturing Phase Example
5.
Event Bubbling
5.1.
Event Bubbling Phase Example
6.
Uses of addEventListener()
7.
Frequently Asked Questions
7.1.
What is addEventListener in JavaScript?
7.2.
What is the use of event listener?
7.3.
What is basic JavaScript event listener?
7.4.
What is event listener capture?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

JavaScript addEventListener() with Examples

Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

The javascript addEventListener() method attaches an event handler to an element in JavaScript without overriding existing event handlers. Events play a crucial role in JavaScript for interactive web development.

If you want to know how JavaScript page loads when an event occurs, I will recommend you read this article on ‘JavaScript Page Load’.

addEventListener

Understanding Events and Event Handlers

An event is nothing but the action that occurs when a user interacts with the computer. An event could, for example, be a keyboard key press or mouse click. A single element or even an entire HTML document might be an event.

When a user interacts with a page, such as by moving their mouse or typing, JavaScript's event handling routine processes those actions. In JavaScript, event handlers take care of both operations once an event is received from an event producer.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is addEventListener () in JavaScript?

Events are the actions or occurrences that occur by the user or by the browser, such as clicking the button, typing in the input field, moving the mouse pointer over the element, etc. These events can be handled by the JavaScript code.

To handle these events, event listeners can be used. These event listeners are attached to the elements in DOM (Document Object Model), such as buttons, links, inputs, images, etc. These event listeners can be added to the elements with the help of the ‘addEventListener’ method. addEventListener is a method that is used to add an event listener to the specific event on the element in the DOM (Document Object Model).

Commonly, addEventListener is used with two arguments that are the name of the event and the function that will be called when the event occurs. Here is the syntax of addEventListener in JavaScript:

Syntax of addEventListener() in JavaScript

element.addEventListener(event, function, useCapture);

 

In the above example, The ‘element’ is the HTML element to which the event listener is to be attached. The ‘event’ shows the specific event that may occur. The ‘function’ is the function that will be called when the event occurs. The ‘useCapture’ is an optional argument that specifies if the event should be handled in the bubbling phase, the value of this either true or false (we will discuss this in detail in the event propagation section).

Here is a simple syntax example of addEventListener:

const ninjaButton = document.querySelector('ninjabutton');

ninjaButton.addEventListener('click', function() {
  console.log(‘Ninja button was clicked!’);
});

 

In the above syntax, addEventListener is used with two arguments first is ‘click’ as an event which shows whenever the user clicks on the ‘ninjaButton’ button element, a ‘click’ event will occur. The second argument is the function that will be called when the ‘click’ event occurs.

Parameters of addEventListener() in JavaScript

There are mainly two compulsory parameters. Let us discuss them in brief.

  • event: It is of string type that indicates the event type to listen for.
  • function: It is a function that the user wants to run when the event occurs.
  • useCapture: This is a boolean value that is false by default. It controls event propagation.

Event Capturing

Event Capturing is the phase where the event occurred on the highest-level element in the DOM hierarchy and also propagates down through the DOM tree until it reaches the target element. 

In other words, we can say capturing phase is when the event of parent and child element triggers no matter what a user clicks.

Event Capturing Phase Example

Code:

<!DOCTYPE html>
<head>
    <title>Capturing Phase Example</title>
</head>
<html>
<body>
    <button id="parent">
        Parent Button
        <button id="child">Child Button</button>
    </button>

    <script>
        const parent = document.querySelector('#parent');
        const child = document.querySelector('#child');

        parent.addEventListener('click', function (event) {
            console.log('Parent clicked during capturing phase!');
        }, true);

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

 

Output in Console:

Console Output 1

 

Explanation: This code example demonstrates event capturing in JavaScript. The parent button event will propagate down to its child button. Event listeners are attached to both buttons to log messages to the console when they are clicked.

When the child button is clicked, the event first triggers the parent button's event listener, which was set to use the capturing phase by setting the third argument to `true` in `parent.addEventListener()`. This will log "Parent clicked during capturing phase!" to the console. The event then continues to propagate down to the child button, triggering its event listener, which will log "Child clicked!" to the console. This shows how events propagate down from parent elements to their children before being handled by an event listener when the useCapture parameter of `addEventListener()` is set to `true`.

Event Bubbling

Event Bubbling is the phase that begins when the event reaches the target element, and bubbling can occur in any event if the event listeners are registered on the parent elements.

In other words, we can say the bubbling phase is when the event of parent and child elements triggers according to the user's click.

As we have the syntax of addEventListener already, but the third argument in addEventListener was still left to discuss, which is ‘useCapture’. The ‘useCapture’ argument specifies the bubbling where by default, most of the events follow the bubbling phase, where the value will be false.

‘useCapture’ can have only two values, true or false. true as the value specifies that the event should be handled during the capture phase, and if the value is false, the event should be handled during the bubbling phase.

Event Bubbling Phase Example

Code:

<!DOCTYPE html>
<head>
    <title>Bubbling Phase Example</title>
</head>
<html>
<body>
    <button id="parent">
        Parent
        <button id="child">Child</button>
      </button>
     
      <script>
        const parent = document.querySelector('#parent');
        const child = document.querySelector('#child');
     
        parent.addEventListener('click', function(event) {
          console.log('Parent clicked!');
        });
     
        child.addEventListener('click', function(event) {
          console.log('Child clicked!');
        });
      </script>
</body>
</html>

 

Output in Console:

Console Output 2

 

Explanation: This code example shows an event bubbling in action, where a child button event will propagate up to its parent button and then to the document object. Event listeners are added to both buttons to log messages to the console when they are clicked. 

If the child button is clicked, the parent button's event listener will be triggered first, logging "Parent clicked!" to the console. The event will then continue to propagate up to the document object, but since there are no more event listeners registered, nothing else will happen. 

Finally, the child button's event listener will execute, logging "Child clicked!" to the console. This demonstrates how event bubbling works in the DOM tree, where events propagate up to parent elements until they are handled by an event listener.

Uses of addEventListener()

There are several use cases of addEventListener in JavaScript, as follows:

  • This method can be used for handling user interactions, as by the action or event, we can analyze what to show the user and what response we should send to the user.
     
  • It can be used for asynchronous programming as a certain event occurs; we can write the function to handle the cases, such as loading the data from the server and calling APIs.
     
  • addEventListener can be used for validating form input inputted by the user in the input field or form.
     
  • This method can be used for handling errors or exceptions such as an event listener can be added to catch the unhandled error and also to show the error on the screen to the user.

Frequently Asked Questions

What is addEventListener in JavaScript?

An event is nothing but the action that occurs when a user interacts with the computer. An event could, for example, be a keyboard key press or mouse click. A single element or even an entire HTML document might be an event. These events can be handled by the JavaScript code.

What is the use of event listener?

Event listeners are used to detect and handle specific events, like user interactions, enabling dynamic behavior in web applications.

What is basic JavaScript event listener?

A basic JavaScript event listener attaches a function to an HTML element, responding to user actions like clicks or keystrokes.

What is event listener capture?

Event listener capture is the phase where the event is captured from the outermost element to the target element, traversing the DOM hierarchy.

Conclusion

In JavaScript, addEventListener is a method that is used to add an event handler function to the HTML element. This function is called when an event occurs on the element. In this article, we discussed what addEventListener is, its syntax, types of events, and event propagation, where we discuss two examples to use addEventListener. We also discussed some of the use cases of addEventListener.

If you want to know how JavaScript page loads when an event occurs, I recommend you read this article on ‘JavaScript Page Load’.

You can refer to our guided paths on the Coding Ninjas Studio platform. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Happy Learning!

Live masterclass