addEventListener()
Attaches an event handler function to an element.
element.addEventListener(type, listener, options?)This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Attaches an event handler function to an element.
addEventListener() registers an event handler to a specific event target, such as an Element, Document, or Window. Unlike legacy 'on-event' properties (e.g., onclick), it supports multiple listeners for the same event type. It operates within the DOM event flow, allowing developers to intercept events during the capturing or bubbling phases. Performance is a key consideration: use the { passive: true } option for scroll and touch listeners to prevent the main thread from waiting on preventDefault() calls, ensuring smoother UI responsiveness. For memory management, ensure listeners are removed if the target persists but the logic is no longer needed. Modern environments support the { signal } option, allowing an AbortController to clean up multiple listeners simultaneously, which is more robust than manual removal.
Quick reference
Syntax
element.addEventListener(type, listener, options?)
Inputs
Parameters
See it in practice
Examples
Basic Click Listener with Options
const button = document.querySelector('#action-btn');
function handleClick(event) {
console.log('Button clicked!');
}
// Listener will only fire once and then self-remove
button.addEventListener('click', handleClick, { once: true });Button clicked! (subsequent clicks trigger nothing)
Uses the 'once' option to ensure the event listener is automatically removed after its first execution.
Optimizing Scroll Performance
window.addEventListener('scroll', function() {
console.log('User is scrolling');
}, { passive: true });User is scrolling
The 'passive' option improves performance by telling the browser the listener will not call preventDefault(), allowing for immediate scrolling optimization.
Cleanup with AbortSignal
const controller = new AbortController();
const { signal } = controller;
window.addEventListener('resize', () => {
console.log('Resized');
}, { signal });
// Remove the listener later by aborting the signal
controller.abort();Resized (stops logging after abort() is called)
Modern approach to remove listeners using AbortSignal, useful for cleaning up multiple listeners at once.
Debug faster
Common Errors
LogicError
Cause: Attempting to remove a listener using an anonymous function or a different function reference than the one registered.
Fix: Store the callback in a variable so the exact same reference can be passed to removeEventListener.
element.addEventListener('click', () => doWork());
element.removeEventListener('click', () => doWork()); // Does nothingTypeError
Cause: Losing 'this' context when passing a class method as a listener.
Fix: Bind the method in the constructor or use an arrow function wrapper.
class App {
setup() {
document.addEventListener('click', this.logEvent);
}
logEvent() {
console.log(this); // 'this' will be the document, not the App instance
}
}Runtime support
Compatibility
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Attaches an event handler function to an element.
type: Event type like 'click' or 'input'. listener: Callback function invoked when the event fires. options: Capture, once, passive, etc.
LogicError: Store the callback in a variable so the exact same reference can be passed to removeEventListener. TypeError: Bind the method in the constructor or use an arrow function wrapper.