JavaScript: addEventListener

addEventListener() registers a function to run when an element receives an event such as a click, input, or submit.

What you will learn

Minimal example

const button = document.querySelector('#save');
function handleClick(event) {
  event.preventDefault();
  console.log('saved');
}

button.addEventListener('click', handleClick);
// Later: button.removeEventListener('click', handleClick);

Keep a reference to the handler function if you need to remove it later. Check that the element exists before registering the listener.

Common mistakes