DEV Community

Ngan Kim Khong
Ngan Kim Khong

Posted on

addEventListener method

The addEventListener() method attaches an event handler to the specified element. Whenever the specified event is delivered to the target element,
the method addEventListener() sets up a function that will be called.

Basically, in an abstract way of saying, the server is just doing its things until the user (a human) interact with it by clicking something on-screen, pressing a button on the keyboard, or they could do anything that a computer is programmed to recognize.

Syntax:
target.addEventListener(event, function, useCapture);

Parameter:
type: Required. A STRING that specifies the name of the event.
You can find more event name as string here:
function: Required. Specifies 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 event object depends on the specified event.

useCapture: Optional. A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.

Example:

You can add events of different types to the same element, in this case, the button.
document.getElementById("myButton").addEventListener("mouseover", myFunction);
document.getElementById("myButton").addEventListener("click", someOtherFunction);
document.getElementById("myButton").addEventListener("mouseout", someOtherFunction);

Using the optional useCapture parameter to show the difference between bubbling and capturing:
document.getElementById("myDiv").addEventListener("click", myFunction, false);
document.getElementById("myDiv").addEventListener("click", myFunction, true);

In this case, only the "true" value from useCapture can be run.

Top comments (0)