freecoding.school100% FREE · NO SIGNUP
The DOM ForestISSUE #19 of 21

custom events · new CustomEvent · dispatchEvent

NodetteVSThe Event Bubbler
Nodette saysCustom events let parts of your app communicate via the DOM with CustomEvent and dispatchEvent.

Create your own events: new CustomEvent("cart:add", { detail: data }), then el.dispatchEvent(evt). Anything listening for "cart:add" receives it, reading payload from event.detail. This decouples components — a sender doesn't need a reference to receivers, mirroring a lightweight pub/sub on the DOM.

Power-ups you unlock

The Event Bubbler attacks — common mistakes

Boss battleDispatch a custom "ping" event with detail and handle it elsewhere.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;padding:20px"><pre id="o"></pre>
<script>document.addEventListener('ping',e=>document.getElementById('o').textContent='got ping: '+e.detail.msg);
document.dispatchEvent(new CustomEvent('ping',{detail:{msg:'hello'}}));</script></body></html>
▶ Open the interactive comic issue
‹ Event Types · Focus · Blur · Load · ResizeTiming · SetTimeout · SetInterval · ClearTimeout ›