Track 02 · Lesson 7 of 17Inside the browser
- 01Events and bubbling
- 02What fires when you click or type
- 03Keyboard, input and focus events
- 04Default actions and preventDefault()
- 05Event delegation
- 06Listener options and cleanup
- 07Custom events
- 08Debounce and throttle
- 09Events in React
- 10The event loop
- 11Don't block the main thread
- 12The rendering pipeline
- 13Core Web Vitals
- 14HTTP caching
- 15Responsive design
- 16SEO basics
- 17Service workers and offline
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
- 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:
detailcarries your data: which product, how much, anything you like.bubblesdecides whether ancestors hear it. It'sfalseby 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