JavaScript HTML DOM EventListener

addEventListener() attaches an event handler to an element, without replacing the handlers that are already there.

element.addEventListener(eventName, handlerFunction, options);
<button id="btn">Like</button>
<p id="count">0</p>
const btn = document.getElementById("btn");
const count = document.getElementById("count");
let likes = 0;

btn.addEventListener("click", () => {
  likes++;
  count.textContent = likes;
});

Each click on the button adds 1 to the number on the page. After 3 clicks, the paragraph shows 3.


The event object

btn.addEventListener("click", (event) => {
  console.log(event.type);
  console.log(event.target.id);
});
Output of the above program is

click
btn


preventDefault

Some events have a default action, like a link that opens a page or a form that sends data. event.preventDefault() stops it.

const link = document.querySelector("a");
link.addEventListener("click", (event) => {
  event.preventDefault();     // do not open the link
  console.log("Link clicked, but not opened");
});

Remove a handler and run once

function sayHi() {
  console.log("Hi");
}

btn.addEventListener("click", sayHi);
btn.removeEventListener("click", sayHi);   // same function reference

btn.addEventListener("click", () => console.log("Only the first time"), { once: true });

To remove a handler you need the same function, so you cannot remove an anonymous function.


Event bubbling and delegation

Most events bubble: after the element, the event goes up to its parent, then the parent of the parent. So you can put one listener on a parent, and handle clicks of all children. This is event delegation, and it also works for elements added later.

const list = document.getElementById("list");

list.addEventListener("click", (event) => {
  if (event.target.tagName === "LI") {
    console.log("Clicked: " + event.target.textContent);
  }
});
Note: Use event.stopPropagation() only when you really must stop the bubbling. It can break other code that listens on parents.

Summary

  • addEventListener(type, handler) adds a handler, and many handlers can be added to one event.
  • Use preventDefault() to stop default actions.
  • Use event delegation for lists and dynamic content.
  • Next: Forms and Validation.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.