Shadow DOM & Events in JavaScript
The Shadow DOM is a way to encapsulate styles and functionality inside a web component, preventing conflicts with the main page. However, handling events in a Shadow DOM works a bit differently than in the regular DOM.
1️⃣ What is Shadow DOM?
Shadow DOM allows you to create a self-contained component with its own isolated styles and markup.
✅ The paragraph inside the Shadow DOM won’t be affected by global styles.
2️⃣ Events in Shadow DOM
Events can pass through the Shadow DOM but have special behavior.
Example: Event Inside Shadow DOM
✅ Events work normally inside the Shadow DOM.
3️⃣ Event Retargeting
When an event happens inside the Shadow DOM, the event.target
behavior differs.
Example: Retargeting
🔹 If you click inside the Shadow DOM, it event.target
will not expose inner elements; instead, it will return the shadow host.
4️⃣ Event Bubbling & Shadow DOM
By default, events bubble up to the main document except for some native events.
✅ The outside event listener can still catch clicks inside the shadow, but event.target
is retargeted.
5️⃣ Dispatching Custom Events from Shadow DOM
If you want an event inside the Shadow DOM to be visible in the main document, use Custom Events.
✅ The composed: true
property allows the event to escape the Shadow DOM and reach the main document.
6️⃣ Preventing Events from Escaping
Some events, like focus
, do not escape the Shadow DOM unless manually dispatched.
🔹 Summary
✔ Shadow DOM keeps styles & elements isolated.
✔ Events inside the Shadow DOM do not expose internal elements.
✔ Use CustomEvent
with composed: true
to allow events to escape.
✔ Some events, like focus
, do not bubble by default.
🚀 Need a hands-on demo? Let me know!