Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

JavaScript Events: Listeners, Bubbling and Event Delegation

5 min read Updated By the SkillNewton team

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 methodWhat it gives you
event.typeThe event name, for example "click"
event.targetThe element that originally triggered the event
event.currentTargetThe element whose listener is running right now
event.keyThe 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 gone

removeEventListener() 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:

  1. Capturing phase: the event travels down from window through each ancestor towards the target.
  2. Target phase: the event reaches the element that was clicked.
  3. 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 });
  • 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, resize and input handlers, or use requestAnimationFrame.
  • Prefer keydown with event.key over the deprecated keypress event and keyCode property.
  • Clean up listeners with once or an AbortController when a component is removed.
  • Wait for DOMContentLoaded or load scripts with defer before 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.

  1. Mark up each question as a <button aria-expanded="false"> followed by an answer panel with the hidden attribute.
  2. Attach one click listener to the wrapper and use closest() to find the button that was clicked.
  3. Toggle hidden on the panel and update aria-expanded to match.
  4. Add a keydown listener so the Up and Down arrow keys move focus between questions.
  5. Add a "Close all" button whose listener is removed with an AbortController when 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.target with event.currentTarget in a delegated listener.
  • Calling stopPropagation() by habit, which breaks delegated listeners higher up the page.
  • Listening for click on a submit button instead of submit on 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.

Want to Learn This Properly?

The PHP Web Development: Foundation & Practical Implementation (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.