JavaScript Element addEventListener() Method Tutorial

In this section, we will learn what the Element addEventListener() method is and how to use it in JavaScript.

What is Element addEventListener() Method in JavaScript?

The JavaScript Element addEventListener() method is used to set an event listener and a handler for an element in an HTML document.

Note: check the document addEventListener section if you’re not familiar with event-listeners and event-handlers in general.

Element addEventListener() Method Syntax:

element.addEventListener(event-name, handler, capture);

Element addEventListener() Method Parameter

The method takes three arguments:

  • The first argument which is required is the name of the event that we want to listen to and invoke a call to a function whenever that event is thrown for the target element in a document.
  • The second argument is a reference to a function that should be invoked whenever the target event is thrown. This reference function is basically the handler method where we put the handling instructions.
  • The last argument is of type boolean and indicates whether the target event should be executed in the bubbling or capturing phase.

Note:

The value true means the event handler should be executed in capturing phase.

And the value false means the handler should be executed in the bubbling phase. (This is the default value)

Element addEventListener() Method Return Value

The method does not return a value.

Example: using element addEventListener() method in JavaScript

See the Pen using element addEventListener() method in JavaScript by Omid Dehghan (@odchan1) on CodePen.

How Does JavaScript addEventListener() Method Work?

In this example, we’ve used the addEventListener() method to add an event to the username box of the page and listened for the click event on this element.

So if we click on this username box, this event will be thrown and the handler (the second argument of the method) will invoke. Inside this handler, we’ve declared a set of instructions that will change the background color of the username box to blue.

Note: as the argument of the handler method, there’s an object that will be passed to it and this object contains information about the event that was thrown. You’ll learn about this object in the event section.

Leave a Reply