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
- How to register a listener for an event type
- How to use the event object and prevent a default action
- How to remove a listener when it is no longer needed
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
- Do not call the handler while registering it; pass the function, not
handleClick(). - Use semantic buttons and forms so keyboard and assistive-technology behavior works before adding custom handlers.
- Use event delegation when many similar child elements are created dynamically, and clean up listeners that outlive their component.