addEventListener
addEventListener
Section titled “addEventListener”Introduction
Section titled “Introduction”addEventListener attaches an event handler to an element without overwriting existing handlers.
Basic Usage
Section titled “Basic Usage”const button = document.querySelector('button');
button.addEventListener('click', function(event) { console.log('Button clicked!'); console.log('Event type:', event.type); // 'click' console.log('Target:', event.target); // The clicked element});
// Multiple listeners on the same elementbutton.addEventListener('click', handler1);button.addEventListener('click', handler2); // Both run independentlyRemoving Listeners
Section titled “Removing Listeners”function handleClick(event) { console.log('Clicked'); button.removeEventListener('click', handleClick); // Runs once}
button.addEventListener('click', handleClick);
// Options: { once: true } — auto-removes after first callbutton.addEventListener('click', handler, { once: true });Options
Section titled “Options”element.addEventListener('click', handler, { capture: false, // Use capture phase instead of bubbling once: false, // Auto-remove after first invocation passive: false // If true, indicates handler won't call preventDefault()});Summary
Section titled “Summary”- Use
addEventListenerinstead ofonclickproperties (supports multiple handlers) - Use
removeEventListenerfor cleanup (requires named function reference) { once: true }for auto-removing handlers- Named functions enable proper removal