addEventListener and the Event Object
Runs a function in response to a browser event, receiving an event object describing what happened and how to control the default behavior.
element.addEventListener(type, handler)
Purpose
addEventListener registers a function to run whenever a given event fires on an element — a
click, a keypress, a form submission, and many others. The handler receives an event object
describing what happened.
Syntax
const button = document.querySelector('#save-button');
button.addEventListener('click', function (event) {
console.log('Clicked:', event.target);
event.preventDefault();
});
Behavior notes
event.targetis the exact element the event originated on — for a click inside a button that contains an icon and text,targetcould be the icon, not the button, depending on exactly where the click landed.event.preventDefault()stops the browser’s default action for that event (a link navigating, a form submitting) without stopping the event from continuing to propagate.- Events bubble: after firing on
target, the same event fires again on each ancestor element in turn, up todocument. This underlies event delegation (covered in the Intermediate tier), which attaches one listener to a parent instead of one per child. removeEventListenerrequires passing the exact same function reference used inaddEventListener— an inline anonymous function can’t be removed later, since there’s no reference to it.
Common mistakes
- Assuming
event.targetis always the element the listener was attached to — it’s whichever element the event actually originated on, which can be a descendant. - Forgetting
preventDefault()on a form’ssubmitevent, causing an unwanted full-page reload. - Attaching an anonymous function when the listener will need to be removed later.
Runtime notes
Part of the DOM standard — browser-only. Node has its own separate EventEmitter pattern for
similar behavior server-side, covered in the Intermediate tier.