JavaScript Interview Question #60

How does addEventListener() work?

DOM, Events & Event Loop Fundamentals Mid-Level Intermediate

Quick Interview Answer

addEventListener registers a callback for a specified event type on an event target. Multiple listeners can be registered for the same event without overwriting one another.

Detailed Explanation

addEventListener registers a callback for a specified event type on an event target. Multiple listeners can be registered for the same event without overwriting one another.

It also accepts an options argument for behavior such as capture, once, and passive. removeEventListener can later remove a listener when supplied with the same event type, callback reference, and compatible capture setting.

Code Example

const button = document.querySelector("#save");

function handleSave(event) {
    console.log("Saving...");
}

button.addEventListener("click", handleSave);

// Later:
button.removeEventListener("click", handleSave);