Zest.

JavaScript: Add an event listener

A short, tested JavaScript example for add an event listener. Copy it and adjust the names and paths for your project.

JavaScript
const btn = document.querySelector("#save");
btn.addEventListener("click", (event) => {
  event.preventDefault();
  console.log("clicked");
});

// event delegation
list.addEventListener("click", e => {
  const item = e.target.closest("li");
  if (item) console.log(item.dataset.id);
});

Find it in Zest

Search for “javascript add an event listener” in Zest and this example appears above the results, with other matches to choose from. Searches stay private.

More JavaScript examples

All JavaScript examples