• 971-553421531
  • info@efaschool.com
  • Dubai(United Arab Emirates)

JavaScript addEventListener( )

javaScript addEventListener( )

The addEventListener( ) method in javaScript is used to attach an event handler to an element. An event handler is a function that is called when a certain event occures, such as mouseclick, or keypress.

The addEventListener( ) method takes three arguments:

  • The first argument is the name of the event. This is the name of the event that you want to listen for, such as click or keydoen.
  • The second argument is the function that you want to call when the event occures. This function is called the event handler.
  • The third argument is an optional boolean value that specifies whether the event handler should be executed in the capturing phase or the bubbling phase. The capturing phase is the first phase of event propagation, and the bubbling phase is the second phase.
JavaScript AddEventListener Code

          
            const button = document.querySelector("button");
            
            button.addEventListener("click", function() {
              console.log("The button was clicked!");
            });
          
        

In this example, We are attaching an event handler to the button element. The event handler is basically a function() and it is called when the click event occures.

The addEventListener( ) method is the recommended way to attach event handler in JavaScript. It has several advantages over the other methods, such as onclick and onmouseover.

  • It allows you attach multiple event handlers to the same element.
  • It allows you specify the event propagation phase.
  • It works on any event target, not just HTML elements.

Here some other things to keep in mind about the addEventListener( ) method

  • The event handler function can be an anonymous function or a named function.
  • The event handler function is called with two arguments: the event object and the target object.
  • The event object contains information about the event, such as the type of the event, the target of the event, and the mouse coordinates(if applicable)
  • The target object is the element that the event occurred on.

Leave a Reply

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