Track 02 · Lesson 7 of 17Inside the browser

Track 02 · Inside the browser

Custom events

Lesson 7 of 17· 5 min

You can create and dispatch your own events. One part of the page announces "an item was added to the cart", and any other part can listen, without the two knowing about each other. Add products and toggle bubbling.

Announce it

Then turn bubbling off

BooklyCart0
The Quiet Orchard$18
Salt and Iron$22
Night Ferry$15
  1. Add a book to the cart.
// The product card announces what happened
card.dispatchEvent(new CustomEvent("cart:add", {
  detail: { name: "Night Ferry", price: 15 },
  bubbles: true,
}));

// The header listens, without knowing about the card
document.addEventListener("cart:add", (event) => {
  count += 1;
  badge.textContent = count;
  console.log(event.detail.name);
});

Dispatching your own event#

new CustomEvent(name, options) creates the event, and element.dispatchEvent(event) sends it. Two options matter:

  • detail carries your data: which product, how much, anything you like.
  • bubbles decides whether ancestors hear it. It's false by default, which surprises almost everyone the first time. With bubbling off, only listeners on the card itself hear the announcement.

Events you dispatch yourself have isTrusted set to false, so nobody can mistake them for a real click.

When to use them#

Custom events shine when the two sides are written separately: web components, widgets dropped into a page, or parts built with different frameworks. Inside one React app, props, state and context are clearer, because you can see who talks to whom.

Check yourself

A card dispatches new CustomEvent(“cart:add”) with no options. Does a listener on document hear it?