JavaScript - addEventListener() method

revision:


Category: EventTarget

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

Common targets are element, or its children, document, and window, but the target may be any object that supports events (such as XMLHttpRequest).

Syntax :

        addEventListener(type, listener)
        addEventListener(type, listener, options)
        addEventListener(type, listener, useCapture)
    

Parameters:

type : a case-sensitive string representing the event type to listen for.

listener : The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be "null", an object with a "handleEvent()"" method, or a JavaScript function.

options : optional. An object that specifies characteristics about the event listener. The available options are:

capture : optional. A boolean value indicating that events of this type will be dispatched to the registered listener before being dispatched to any "EventTarget" beneath it in the DOM tree. If not specified, defaults to false.
once: optional. A boolean value indicating that the "listener" should be invoked at most "once" after being added. If true, the listener would be automatically removed when invoked. If not specified, defaults to "false".
passive : optional. A boolean value that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. If not specified, defaults to false – except that in browsers other than Safari, defaults to true for the wheel, mousewheel, touchstart and touchmove events. See Improving scrolling performance with passive listeners to learn more.
signal : optional. An "AbortSignal". The listener will be removed when the given AbortSignal object's abort() method is called. If not specified, no AbortSignal is associated with the listener.

useCapture : optional. A boolean value indicating whether events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events that are "bubbling" upward through the tree will not trigger a listener designated to use capture. Event "bubbling" and "capturing" are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event. If not specified, useCapture defaults to false.

wantsUntrusted : optional. A Firefox (Gecko)-specific parameter. If true, the listener receives synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). This parameter is useful for code found in add-ons, as well as the browser itself.

Examples:

            function eventHandler(event) {
                if (event.type === "fullscreenchange") {
                  /* handle a full screen toggle */
                } else {
                  /* handle a full screen toggle error */
                }
            }

            let passiveSupported = false;
            try {
            const options = {
                get passive() {
                // This function will be called when the browser
                // attempts to access the passive property.
                passiveSupported = true;
                return false;
                },
            };
            window.addEventListener("test", null, options);
            window.removeEventListener("test", null, options);
            } catch (err) {
            passiveSupported = false;
            }
        

Category: document

The addEventListener() method attaches an event handler to a document.

Syntax :

        document.addEventListener(event, function, capture)
    

Parameters:

event : required. The event name. Do not use the "on" prefix. Use "click" instead of "onclick".

function : required. The function to run when the event occurs. When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object.

capture : optional. Default = false. "true" - The handler is executed in the capturing phase. "false" - The handler is executed in the bubbling phase.

Examples:

            <p>Click anywhere in the document to display "Hello World!".</p>
            <p id="demo"></p>
            <script>
                document.addEventListener("click", myFunction);
                function myFunction() {
                    document.getElementById("demo").innerHTML = "Hello World";
                }
            </script>

            <p>Click anywhere in the document to display "Hello World!".</p>
            <p id="demo"></p>
            <script>
                document.addEventListener("click", function(){
                document.getElementById("demo").innerHTML = "Hello World!";
            });
            </script>

        

Category: element

The addEventListener() method attaches an event handler to an element.

Syntax :

        element.addEventListener(event, function, useCapture)
    

Parameters:

event : required. The event name. Do not use the "on" prefix. Use "click" instead of "onclick".

function : required. The function to run when the event occurs.

useCapture : optional. Default = false. "true" - The handler is executed in the capturing phase. "false" - The handler is executed in the bubbling phase.

Examples:

            <p>Execute a function when a user clicks on a button:</p>
            <button id="myBtn">Try it</button>
            <p id="demo">
            <script>
                const element = document.getElementById("myBtn");
                element.addEventListener("click", myFunction);
                function myFunction() {
                    document.getElementById("demo").innerHTML = "Hello World";
                }
            </script>

            <p>Attach a click event to a button:</p>
            <button id="myBtn">Try it</button>
            <p id="demo"></p>
            <script>
                const element = document.getElementById("myBtn");
                element.addEventListener("click", function() {
                    document.getElementById("demo").innerHTML = "Hello World";
                });
            </script>
        

Practical examples

add a simple eventlistener

click with mouse on an element.

one
two
code:
                    <div>
                        <table id="outside">
                            <tr>
                            <td id="t1">one</td>
                            </tr>
                            <tr>
                            <td id="t2">two</td>
                            </tr>
                        </table>
                    </div>
                    <script>
                        // Function to change the content of t2
                        function modifyText() {
                        const t2 = document.getElementById("t2");
                        const isNodeThree = t2.firstChild.nodeValue === "three";
                        t2.firstChild.nodeValue = isNodeThree ? "two" : "three";
                        }
                        // Add event listener to table
                        const el = document.getElementById("outside");
                        el.addEventListener("click", modifyText, false);
                        
                    </script>
                

add an abortable listener

addEventListener() can be aborted with an AbortSignal.

one
two
code:
                    <table id="outside1">
                        <tr>
                        <td id="t11">one</td>
                        </tr>
                        <tr>
                        <td id="t22">two</td>
                        </tr>
                    </table>
                    </div>
                    <script>
                            // Add an abortable event listener to table
                            const controller = new AbortController();
                            const elem = document.getElementById("outside1");
                            elem.addEventListener("click", modifyText1, { signal: controller.signal });
                            // Function to change the content of t2
                            function modifyText1() {
                                const t22 = document.getElementById("t22");
                                if (t22.firstChild.nodeValue === "three") {
                                    t22.firstChild.nodeValue = "two";
                                } else {
                                    t22.firstChild.nodeValue = "three";
                                    controller.abort(); // remove listener after value reaches "three"
                                }
                            }
                        
                    </script>
                

use the addEventListener() method to add many events on the same button.

code:
                    <div>
                        <button id="Btn_A">Try it</button>
                        <p id="add-1"></p>
                    </div>
                    <script>
                        const element = document.getElementById("Btn_A");
                        element.addEventListener("mouseover", mouseFunction);
                        element.addEventListener("click", clickFunction);
                        element.addEventListener("mouseout", mouse2Function);
            
                        function mouseFunction() {
                            document.getElementById("add-1").innerHTML += "Moused over!<br>"
                        }
                        function clickFunction() {
                            document.getElementById("add-1").innerHTML += "Clicked!<br>"
                        }
                        function mouse2Function() {
                            document.getElementById("add-1").innerHTML += "Moused out!<br>"
                        }
                    </script>
                

the difference between bubbling and capturing:

Click this paragraph, I am Bubbling.


Click this paragraph, I am Capturing.

code:
                    <div>
                        <div id="myDiv">
                            <p id="myP">Click this paragraph, I am Bubbling.</p>
                        </div><br>
                        
                        <div id="myDiv2">
                            <p id="myP2">Click this paragraph, I am Capturing.</p>
                        </div>
                        <p id="add-2"></p>
                    </div>
                    <style>
                        div #myP, div #myP2 {background-color: coral; padding: 1.6vw; }
                    </style>
                    <script>
                        document.getElementById("myP").addEventListener("click", function() {
                            myDisplay("You clicked the P element!");
                        }, false);
            
                        document.getElementById("myDiv").addEventListener("click", function() {
                            myDisplay("You clicked the DIV element!");
                        }, false);
            
                        document.getElementById("myP2").addEventListener("click", function() {
                            myDisplay("You clicked the P element!");
                        }, true);
            
                        document.getElementById("myDiv2").addEventListener("click", function() {
                            myDisplay("You clicked the DIV element!");
                        }, true);
            
                        function myDisplay(text) {
                            document.getElementById("add-2").innerHTML += text + "<br>";
                        }
                        
                    </script>
                

click anywhere in the document to perform a calculation.

code:
                    <div>
                        <p id="add-3"></p>
                        <p id="add-4"></p>
                    </div>
                    <script>
                        let p1 = 5;
                        let p2 = 7;
                        document.getElementById('add-3').innerHTML = "value p1 = " + p1 + " ; " + " value p2 = " + p2;
                        document.addEventListener("click", function() {
                            calculate(p1, p2);
                        });
            
                        function calculate(a, b) {
                            let result = a * b;
                            document.getElementById("add-4").innerHTML = "total = " + result;
                        }
                    </script>