JavaScript addEventListener()

The addEventListener function serves the purpose of linking an event handler to a specific element. It does not replace any previously established event handlers. Events are considered a fundamental aspect of JavaScript. A web page reacts based on the event that takes place. Events may originate from user interactions or be triggered by APIs. An event listener is a JavaScript function designed to monitor the occurrence of an event. For instance, it can respond to events such as click, keydown, or submit.

The addEventListener function is an integral part of the DOM API rather than a feature of JavaScript directly. This method allows us to attach numerous event handlers to a specific element without replacing any of the current event handlers that may already be in place.

Syntax

Example

element.addEventListener(event, function, useCapture);

While there are three parameters in total, the parameters event and function are the most commonly utilized. The third parameter, useCapture, is an optional specification. The possible values for this function are outlined as follows.

Description

element: This refers to a DOM element that the developer intends to monitor for events, which may include the document, button, or div.

event: This parameter is mandatory. It can be characterized as a string that denotes the name of the event.

Note: Do not use any prefix such as "on" with the parameter value. For example, use click instead of "onclick".

function: This is a mandatory parameter, which represents a JavaScript function designed to react to the occurrence of the specified event.

useCapture: This parameter is optional. It is of the Boolean type and indicates whether the event should be processed during the capturing phase or the bubbling phase. The values it can take are true and false. When assigned a value of true, the event handler will run in the capturing phase. Conversely, if it is set to false, the handler will operate in the bubbling phase. By default, this value is false.

How does JavaScript addEventListener Work?

In JavaScript, the method addEventListener is utilized to monitor a specific event occurring on a designated element. Upon the occurrence of that event, it triggers the execution of particular code as a response. The addEventListener function associates an event handler with an element, executing a defined block of code whenever the specified event successfully occurs. These events can originate from user interactions, such as clicks or key presses, or may be initiated by various APIs.

The addEventListener function is not restricted solely to HTML and SVG elements; it can also be applied to any DOM object, including the window object itself.

Let’s explore a few examples that demonstrate how to utilize the addEventListener function.

Example 1: A simple example of AddEventListener

This is a straightforward illustration of utilizing the addEventListener function. To observe the outcome, you need to click the specified HTML button.

Example

Example

<!DOCTYPE html>  

<html>  

<body>  

<p> Example of the addEventListener() method. </p>  

<p> Click the following button to see the effect. </p>  

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

<p id = "para"></p>  

<script>  

document.getElementById("btn").addEventListener("click", fun);  

function fun() {  

document.getElementById("para").innerHTML = "Hello World" + "<br>" + "Welcome to the  logic-practice.com";  

}  

</script>  

</body>  

</html>

Output:

Upon selecting the specified HTML button, the resulting output will be -

Explanation:

In the code presented above, we established some HTML elements. Specifically, we generated a button labeled Click Me and assigned it an identifier of btn. Additionally, we created a paragraph element, which we tagged with the id para. In the JavaScript portion, we retrieve the button using its designated id. We implemented an addEventListener for the button. A function called fun was defined, which utilizes innerHTML to insert content into the HTML via JavaScript.

Example 2: Adding multiple addEventListener

In this instance, we will explore the method of attaching multiple events to a single element while ensuring that the pre-existing events remain intact.

Example

Example

<!DOCTYPE html>  

<html>  

<body>  

<p> This is an example of adding multiple events to the same element. </p>  

<p> Click the following button to see the effect. </p>  

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

<p id = "para1"></p>  

<p id = "para2"></p>  	

<script>  

function fun1() {  

    alert("Welcome to the logic-practice.com");  

}  	

   

function fun2() {  

   document.getElementById("para1").innerHTML =  "This is second function";  

  

}  

function fun3() {  

   document.getElementById("para2").innerHTML =  "This is third function";  

}  

var mybtn = document.getElementById("btn");  

mybtn.addEventListener("click", fun1);  

mybtn.addEventListener("click", fun2);  

mybtn.addEventListener("click", fun3);  

</script>  

</body>  

</html>

Output:

At this point, upon clicking the button, an alert box will appear. The result after clicking the specified HTML button will be:

When we exit the alert, the output is:

Explanation:

In the code presented above, we established a button designated with the identifier btn. Additionally, we generated two empty paragraphs using the <p> tag, assigned with the identifiers para1 and para2, which will be utilized for displaying messages at a later stage. Furthermore, we defined three functions labeled fun1, fun2, and fun3.

The function designated as fun1 is defined to display an alert containing the message "Welcome to the logic-practice.com ". The subsequent function, referred to as fun2, which possesses an identifier para1, is outlined here to modify the content. The third function, known as fun3 and identified by para2, is specified to alter the content as well.

Through the use of addEventListener, three distinct functions are linked to a single click event. Therefore, when the "Click me" button is pressed, an alert box appears, followed by the display of the first paragraph, and ultimately, the second paragraph is shown.

Example: Adding multiple events of different types to the same element.

In this illustration, we will be incorporating various types of events to the same element using the addEventListener method.

Example

Example

<!DOCTYPE html>  

<html>  

<body>  

<p> This is an example of adding multiple events of different type to the same element. </p>  

<p> Click the following button to see the effect. </p>  

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

<p id = "para"></p>  

<script>  

function fun1() {  

    btn.style.width = "50px";  

    btn.style.height = "50px";  

    btn.style.background = "yellow";  

    btn.style.color = "blue";  

}  

   

function fun2() {  

   document.getElementById("para").innerHTML =  "This is second function";  

  

}  

function fun3() {  

    btn.style.width = "";  

    btn.style.height = "";  

    btn.style.background = "";  

    btn.style.color = "";  

}  

var mybtn = document.getElementById("btn");  

mybtn.addEventListener("mouseover", fun1);  

mybtn.addEventListener("click", fun2);  

mybtn.addEventListener("mouseout", fun3);  

</script>  

</body>  

</html>

Output:

As we hover the cursor over the button, the resulting output will be:

Upon clicking the button and removing the cursor, the resulting output will be:

Explanation:

In the code provided above, we established a button identified by the id btn. Additionally, we generated an empty paragraph assigned the id para, which serves as the display area for content following a click on the button. We defined a function called fun1. Within this function, a mouseover event listener is incorporated, which applies styling to the button whenever a user hovers their cursor over it.

A second function has been established, referred to as fun2. This function serves as a click event that modifies the paragraph identified by the id para to show updated content. Additionally, a third function, designated as fun3, has been implemented to restore the button's style. This function operates as a mouseout event, returning the button's appearance to its default state.

Therefore, when a user places their cursor over the button, the fun1 function is activated, causing the button to diminish in size and change its color to yellow with blue text. Upon clicking the button, the fun2 function is invoked, resulting in the message "This is the second function" being shown. When the mouse pointer leaves the button area, the fun3 function is triggered, which restores the button to its original style.

Adding Event Handlers to the window Object

In JavaScript, the window object serves to represent the browser's window object. It can be employed to monitor events that take place on a global scale throughout the whole window. For instance, this includes actions such as resizing the window, scrolling, or detecting keypress events.

Example:

Let’s explore how to incorporate event handlers into the window object by examining a practical example.

Example

Example

<!DOCTYPE html>

<html>

<head>

    <title>Interactive Window Event Handlers</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            text-align: center;

            margin: 0;

            padding: 20px;

            height: 2000px;

            transition: background-color 0.3s ease;

        }



        #myMessage {

            font-size: 20px;

            font-weight: bold;

            margin-top: 20px;

            padding: 10px;

        }



        #myKeyPressDisplay {

            font-size: 24px;

            font-weight: bold;

            margin-top: 30px;

            color: #333;

        }

    </style>

</head>

<body>



    <h1>Interact with the Page!</h1>

    <div id="myMessage">Resize the window, scroll down, or press a key!</div>

    <div id="myKeyPressDisplay"></div>



    <script>

        const myMessage = document.getElementById('myMessage');

        const myKeyPressDisplay = document.getElementById('myKeyPressDisplay');



        // Window Resize Event

        window.addEventListener('resize', function () {

            const width = window.innerWidth;

            const height = window.innerHeight;

            myMessage.innerText = `Window resized! New dimensions: ${width}x${height}`;



            myMessage.style.fontSize = (width / 50) + 'px';

        });

        window.addEventListener('scroll', function () {

            const scrollY = window.scrollY;

            document.body.style.backgroundColor = `rgb(${scrollY % 255}, ${255 - (scrollY % 255)}, 150)`;



            myMessage.innerText = `You have scrolled! Scroll position: ${scrollY}px`;

        });



        // Window Keydown Event

        window.addEventListener('keydown', function (event) {

            myKeyPressDisplay.innerText = `You pressed the "${event.key}" key!`;



            if (event.key === 'Enter') {

                myKeyPressDisplay.style.color = 'green';

            } else if (event.key === 'Escape') {

               myKeyPressDisplay.style.color = 'red';

            } else {

                myKeyPressDisplay.style.color = '#333';

            }

        });

    </script>



</body>

</html>

Output:

When we execute code, the output will be:

As we navigate downward on the page, the background color will transition, resulting in the following output:

As we adjust the dimensions of the page, the measurements will be shown in accordance with the new size of the page:

Explanation:

In the preceding illustration, a heading is established alongside a message. We constructed a div element and assigned it an identifier called myMessage, which is employed to present the dynamic message triggered by resize and scroll events. Additionally, another div is generated with the identifier myKeyPressDisplay, which serves to exhibit the key that the user has pressed. The elements myMessage and myKeyPressDisplay are accessed using JavaScript and are stored in the variables myMessage and myKeyPressDisplay, respectively.

We implemented a window resize event utilizing window.addEventListener. This event activates whenever the browser window is resized. It reflects the modifications in width and height, adjusting the font size in response to the screen dimensions. Additionally, we incorporated a window scroll event that activates when a user scrolls through the page, altering the background color accordingly. Furthermore, a window keydown event has been integrated, which is triggered when any key is pressed by the user. This event indicates which key has been pressed. Specifically, when the Enter key is pressed, it is highlighted in green, the Escape key is shown in red, and all other keys are displayed in gray.

Event Bubbling or Event Capturing

At this point, we will explore the functionality of the third argument in JavaScript's addEventListener method, specifically the useCapture parameter.

Within the HTML Document Object Model (DOM), event propagation occurs through two primary methods: Bubbling and Capturing. To better comprehend these methods, we can illustrate them with an example.

Consider a scenario where you have a div element containing a paragraph element within it, and you are utilizing the addEventListener method to assign a "click" event to both elements. The question that arises is: when the paragraph element is clicked, which element's click event will be processed first?

In the Bubbling phase, the event associated with the paragraph element is processed prior to the event of the div element. This indicates that during bubbling, the events for the inner elements are addressed first, followed by the handling of events for the outermost elements.

In the capturing phase, the event associated with the div element is processed prior to the event of the paragraph element. This indicates that during the capturing process, the event for the outermost element is addressed first, followed by the handling of the event for the innermost element.

Example

addEventListener(event, function, useCapture);

The propagation mechanism can be defined by utilizing the useCapture parameter. If this parameter is assigned a value of false, which is its default setting, the event will follow the bubbling propagation method. Conversely, if the parameter is set to true, it will employ capturing propagation.

To grasp the concepts of bubbling and capturing, we can utilize a visual example.

Example

In this illustration, there exist two div elements. The bubbling effect is observable on the initial div element, while the capturing effect is evident on the subsequent div element.

When we perform a double-click on the span element located within the first div element, the event associated with the span element is processed prior to that of the div element. This phenomenon is referred to as bubbling.

However, when we perform a double-click action on the span element located within the second div element, the event associated with the div element is processed prior to that of the span element. This phenomenon is referred to as capturing.

Example

Example

<!DOCTYPE html>

<html>

<head>

    <title>Event Bubbling vs Capturing</title>

    <style>

        #parent {

            background-color: blue;

            padding: 20px;

            margin: 20px;

        }



        #child {

            background-color: green;

            color: white;

            cursor: pointer;

            padding: 20px;

            margin: 20px;

        }

    </style>

</head>

<body>



    <div id="parent">

        <p id="child">Click me!</p>

    </div>



    <script>

        const parent = document.getElementById('parent');

        const child = document.getElementById('child');

        parent.addEventListener('click', function() {

            alert('Parent Div Clicked (Capturing)');

        }, true);



        child.addEventListener('click', function() {

            alert('Child Div Clicked (Bubbling)');

        }, false);

    </script>



</body>

</html>

Output:

Upon executing the code, an option labeled Click me! will become available.

Upon clicking the "Click me!" button, an alert dialog appears displaying the message, "Parent Div Clicked (Capturing)".

Upon clicking the OK button, an additional alert box appears displaying the message "Child Div Clicked (Bubbling)."

Explanation:

In the code presented above, there exists a parent div identified by the id parent, which contains a blue box. Within this parent div, there is a child paragraph that is assigned the id child, featuring a green color with the text Click me displayed in white. We utilize JavaScript to interact with these elements and incorporate functionality.

In the example parent.addEventListener('click', …, true); the third argument, set to true, indicates that the event is processed during the capturing phase. This means that the event travels from the bottommost element up to the target element while it is in the capturing process.

Therefore, when we engage the "Click me" button, which acts as a child element, the event handler associated with the parent element is triggered first due to the event capturing phase occurring prior to the bubbling phase. The method child.addEventListener('click',…false) indicates that the event listener is set to the bubbling phase. During bubbling, the event travels from the target element up to the root of the DOM. Consequently, after the parent’s capturing event handler has been executed, the event handler for the child element in the bubbling phase is executed next.

Upon clicking the child's "Click me" button, the event enters the capture phase. The parent then triggers an alert displaying "Parent Div Clicked." Following this, the event transitions into the bubbling phase, where the child triggers an alert that says "Child Div Clicked."

Remove EventListener Method:

To eliminate an event listener, it is necessary to utilize the removeEventListener method. This method allows us to detach an event listener that was previously attached using the addEventListener method. It is crucial to remember that the same parameters must be supplied as those used during the addition of the event listener with addEventListener. The event type, the callback function, and the useCapture flag must all match the original values.

Eliminating event listeners is crucial as it helps avoid memory leaks, enhances performance, and ensures that applications function correctly.

Example:

Let’s explore the functionality of removeEventListener through an illustrative example.

Example

Example

<!DOCTYPE html>

<html>

<head>

  <title>removeEventListener Example</title>

  <style>

    #myBtn {

      background-color: green;

      color: white;

      padding: 10px 20px;

      cursor: pointer;

      border: none;

      border-radius: 5px;

    }

  </style>

</head>

<body>



  <button id="myBtn">Click Me!</button>

  <button id="removeBtn">Remove Event Listener</button>



  <script>

    const myBtn = document.getElementById("myBtn");

    const removeBtn = document.getElementById("removeBtn");



    // Define a function (must be a named function, not anonymous)

    function sayHello() {

      alert("Button Clicked!");

    }



    // Add event listener to button

    myBtn.addEventListener("click", sayHello);



    // Remove event listener when second button is clicked

    removeBtn.addEventListener("click", function () {

      myBtn.removeEventListener("click", sayHello);

      alert("Event listener removed. Now the button won't respond.");

    });

  </script>



</body>

</html>

Output:

When you click on the Click Me! button:

Upon clicking the Remove Event Listener button:

Explanation:

The script assigns a click event listener named sayHello to the initial button, which triggers an alert upon being clicked. Additionally, it includes a second button that, when pressed, invokes the removeEventListener method to unlink the sayHello function from the first button, thereby stopping it from reacting to any subsequent clicks.

Best Practices

Some best practices that we should follow when we use event listeners are as follows:

  • Use named functions : We should always try to utilize named functions when possible. It keeps our code cleaner and effortless to handle and manage.
  • Always utilize event.preventDefault and event.stopPropogation : These methods help us to control the behaviour of events and prevent unnecessary side effects.
  • Use removeEventListener : When we no longer need an event, then we should remove the attached event.
  • Conclusion:

In JavaScript, the addEventListener method is a crucial concept that enables the attachment of event listeners to various HTML DOM elements. This includes objects such as the HTML document, the window object, HTML elements, or other event-capable objects, such as the XMLHttpRequest object. This article will explore the JavaScript addEventListener method, providing examples along with a section addressing commonly asked questions.

FAQs:

  1. What does addEventListener do in JavaScript?

The method addEventListener in JavaScript allows us to attach an event handler to a specific HTML element. This functionality enables us to specify a function that will execute when a certain event, such as a click, keypress, or mouse movement, takes place on that element.

  1. Can we attach multiple event listeners of the same type to a single element?

Indeed, it is possible to attach numerous event listeners of the identical type to a single element.

All of them will be executed when the specified event takes place on the webpage.

  1. What is the method to removeEventListener?

The method removeEventListener can be employed to detach an event. It is necessary to provide the identical event type, listener function, and options or useCapture (if it was specified) in the same manner as when the event listener was originally added.

  1. Is it essential to eliminate event listeners?

Indeed, it is considered a best practice to detach event listeners in JavaScript. This approach aids in avoiding memory leaks, particularly in single-page applications where elements may be added or removed dynamically.

  1. Is it possible to attach an event listener to the document or window objects?

Indeed, it is possible to attach an event listener to both the document and the window to monitor global events.

  1. What are some of the typical event types that can be utilized with addEventListener?

In JavaScript, the frequently utilized event types associated with addEventListener include click, mouseover, mouseout, keydown, keyup, load, resize, scroll, among others.

Input Required

This code uses input(). Please provide values below: