JavaScript Events: Listeners, Bubbling and Event Delegation
What are events in JavaScript?
Events are signals the browser sends when something happens on a page, such as a click, a key press, a form submission or the page finishing loading. JavaScript reacts by registering a listener with addEventListener(). The listener receives an event object describing what happened, and it can read details, stop default behaviour or pass work to other code.
Event terminology: types, targets, listeners and the event object
Every event has a type, a string such as click, input, submit, keydown or DOMContentLoaded. The element where it happened is the target. A listener (or handler) is the function you register to run when that type of event reaches an element.
| Property or method | What it gives you |
|---|---|
event.type | The event name, for example "click" |
event.target | The element that originally triggered the event |
event.currentTarget | The element whose listener is running right now |
event.key | The key pressed, for keyboard events, such as "Enter" |
event.preventDefault() | Cancels the browser's default action, such as following a link |
event.stopPropagation() | Stops the event travelling to further elements |
The difference between target and currentTarget matters as soon as elements are nested. Click a <span> inside a button and the target is the span, while a listener on the button sees the button as its current target.
Adding and removing listeners with addEventListener
addEventListener(type, listener, options) attaches a function without replacing any other listeners on the same element, which is why it is preferred over inline onclick attributes or assigning element.onclick.
const button = document.querySelector('#save');
function handleSave(event) {
console.log(event.type, event.currentTarget.id); // "click" "save"
}
button.addEventListener('click', handleSave);
button.removeEventListener('click', handleSave); // same function reference
// Options object
button.addEventListener('click', handleSave, { once: true }); // runs one time, then removes itself
// Remove several listeners at once with an AbortController
const controller = new AbortController();
window.addEventListener('resize', () => console.log(innerWidth), { signal: controller.signal });
document.addEventListener('keydown', e => console.log(e.key), { signal: controller.signal });
controller.abort(); // both listeners are goneremoveEventListener() only works when you pass the same function reference and the same capture setting you used when adding it. An anonymous arrow function written inline cannot be removed this way, which is where the signal option helps.
How events travel: capturing, target and bubbling phases
When you click a nested element, the event does not just fire on that element. It moves through the DOM in three phases:
- Capturing phase: the event travels down from
windowthrough each ancestor towards the target. - Target phase: the event reaches the element that was clicked.
- Bubbling phase: the event travels back up through the ancestors to
window.
Listeners run in the bubbling phase by default. Pass { capture: true } to run during the capturing phase instead, which lets a parent see an event before its children do.
// <div id="card"><button id="buy">Buy</button></div>
card.addEventListener('click', () => console.log('card (capture)'), { capture: true });
card.addEventListener('click', () => console.log('card (bubble)'));
buy.addEventListener('click', () => console.log('button'));
// Clicking the button logs:
// card (capture)
// button
// card (bubble)Most events bubble, but not all. focus and blur do not; use focusin and focusout when you need bubbling versions. mouseenter and mouseleave also do not bubble, unlike mouseover and mouseout.
Event delegation: one listener for many elements
Because events bubble, a single listener on a parent can handle events from every child, including children added later. This is event delegation. Use event.target.closest() to find the relevant child, because the click may land on an icon or text inside it.
// <ul id="courses"> with many <li><button data-id="12">Enrol</button></li>
const list = document.querySelector('#courses');
list.addEventListener('click', event => {
const button = event.target.closest('button[data-id]');
if (!button || !list.contains(button)) return; // click was elsewhere
console.log('Enrol in course', button.dataset.id);
});Delegation reduces the number of listeners and removes the need to attach new ones every time you render items, a pattern used throughout the DOM manipulation guide. Use stopPropagation() sparingly: it silently breaks any delegated listener higher up the tree, including analytics and accessibility scripts.
preventDefault, passive listeners and form events
Many events have a default action: a link navigates, a form submits and reloads the page, a checkbox toggles. event.preventDefault() cancels that action but does not stop propagation. The common case is handling a form in JavaScript, as shown in our guide to HTML forms.
const form = document.querySelector('#signup');
form.addEventListener('submit', event => {
if (!form.email.value.includes('@')) {
event.preventDefault(); // stay on the page
form.email.setCustomValidity('Enter a valid email address');
form.reportValidity();
}
});
form.email.addEventListener('input', () => form.email.setCustomValidity(''));Passive listeners for scroll and touch
For touchstart, touchmove and wheel, the browser must wait to see whether a listener calls preventDefault() before it can scroll. Marking the listener { passive: true } promises that it will not, so scrolling stays smooth. Chrome and Firefox already treat these listeners as passive when attached to window, document or body; inside a passive listener, preventDefault() is ignored and logs a console warning.
document.addEventListener('touchmove', updateIndicator, { passive: true }); Recommended event-handling practices
- Use real
<button>and<a>elements so click handlers also respond to Enter and Space, as covered in the web accessibility guide. - Throttle or debounce expensive work in
scroll,resizeandinputhandlers, or userequestAnimationFrame. - Prefer
keydownwithevent.keyover the deprecatedkeypressevent andkeyCodeproperty. - Clean up listeners with
onceor anAbortControllerwhen a component is removed. - Wait for
DOMContentLoadedor load scripts withdeferbefore selecting elements.
Practical exercise: an accessible accordion with delegation
Build a FAQ accordion with five questions, using the language basics from our introduction to JavaScript.
- Mark up each question as a
<button aria-expanded="false">followed by an answer panel with thehiddenattribute. - Attach one click listener to the wrapper and use
closest()to find the button that was clicked. - Toggle
hiddenon the panel and updatearia-expandedto match. - Add a
keydownlistener so the Up and Down arrow keys move focus between questions. - Add a "Close all" button whose listener is removed with an
AbortControllerwhen the accordion is destroyed.
You are done when the accordion works with mouse and keyboard, new questions added with JavaScript respond without extra listeners, and the console shows no errors. Interactive front ends like this are built alongside PHP back ends in SkillNewton's PHP foundation course.
Common mistakes
- Calling the handler instead of passing it, as in
addEventListener('click', save()), which runs it once immediately. - Trying to remove an anonymous function with
removeEventListener(), which silently does nothing. - Confusing
event.targetwithevent.currentTargetin a delegated listener. - Calling
stopPropagation()by habit, which breaks delegated listeners higher up the page. - Listening for
clickon a submit button instead ofsubmiton the form.
Frequently asked questions
What is the difference between onclick and addEventListener?
Setting element.onclick stores one handler, and assigning again replaces it. addEventListener() can attach any number of listeners and supports options such as capture, once, passive and signal.
Does preventDefault stop event bubbling?
No. preventDefault() only cancels the browser's default action. The event still bubbles to ancestors unless you also call stopPropagation().
Can I create my own events?
Yes. Create one with new CustomEvent('cart:updated', { detail: { count: 3 }, bubbles: true }) and fire it with element.dispatchEvent(). Listeners read the data from event.detail.
When should I use the capture phase?
Rarely. It is useful when a parent must react before any child handler runs, for example to close an open menu when a click happens anywhere on the page.