Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Shadow DOM and Styling

Shadow DOM Events and Focus

Understand how events cross shadow boundaries: retargeting, composed and bubbles, composedPath, which built-in events escape, plus delegatesFocus, tabindex and focus behavior.

A shadow root hides a component's internal elements. But the page still needs to hear when a user clicks inside it, and the browser still needs to know which element has focus. Events and focus are the two places where the shadow boundary behaves in ways that surprise people. This lesson explains the rules so you can predict what event.target is, which events escape, and how keyboard focus flows through a component.

Events cross the boundary, with changes

When a user clicks a button inside a shadow tree, the browser dispatches a click event whose path goes up through the shadow tree, through the host, and on to the page. Two things change at the boundary.

  1. Retargeting. For listeners outside the shadow tree, event.target is rewritten to the host. The page never sees the inner button, which keeps the internals private.
  2. Some events stop. An event only leaves the shadow root if its composed flag is true.
Retargeting in action

Click the button. Inside the shadow tree, target is the real BUTTON. In the page's listener, it is inner-button, the host. Yet composedPath() still reveals the full path (for an open shadow root): button > #document-fragment > inner-button > div. Closed roots hide the inner part of the path.

flowchart BT
  B["button (real target)"] --> SR["#shadow-root"]
  SR --> H["inner-button (host)"]
  H --> D["div#page"]
  D --> Doc["document"]

A click bubbles up through the shadow root and the host. Outside, target is the host.

Which events are composed?

Browser-generated UI events are composed: click, dblclick, pointerdown, pointerup, mousedown, touchstart, keydown, keyup, focus, blur, input (not change), beforeinput, wheel, and similar. Some events are not composed: change, load, error, scroll, select, slotchange, mouseenter and mouseleave (which do not bubble anyway).

This detail bites with forms. A native <input> inside your component fires input that leaves, but change stays inside. If page code needs change, your component must re-dispatch it. That is the topic of Events in Lit.

Custom events: bubbles and composed

An event you create with new CustomEvent("name") has bubbles: false and composed: false by default. It reaches only listeners on the host itself, not ancestors. Set both flags when you want it to behave like a native event:

Custom events across the boundary

The first event is dispatched on an element inside the shadow root with no flags, so it dies at the shadow root. The second leaves the root, bubbles through the host to #app. In Lit components, the rule of thumb is to dispatch from this (the host): this.dispatchEvent(new CustomEvent("value-change", { detail, bubbles: true, composed: true })). Dispatching on the host means listeners attached directly to the tag always work. Dispatching with composed: true from deep inside is needed only for events that originate in nested shadow roots.

Keep in mind that composed: true makes the event visible across every boundary above it. A generic name like change or select could confuse listeners higher up. Prefix event names: acme-select.

Listening: delegation and the path

Event delegation, which means one listener on a container and checking event.target, works inside a shadow root but sees the retargeted target when the listener is outside. If a list component wants to react to clicks on its items, attach the listener inside the shadow tree (Lit's @click on the container does this), where target is still the real element.

When you need the real origin from outside, use event.composedPath()[0]. With an open root it returns the true target. With closed roots it returns the host.

Focus and the shadow boundary

Focus follows similar rules. If an input inside a shadow root has focus, then for page code document.activeElement is the host, and the real element is host.shadowRoot.activeElement. Focus events are composed, but focus and blur do not bubble; use focusin and focusout to catch them on ancestors.

Who has focus?

When you focus the inner input, the page-level activeElement reports focus-box, the retargeted host. Only the shadow root knows the real element.

delegatesFocus

By default, a custom element is not focusable, and clicking its non-interactive areas does not focus anything. If you pass delegatesFocus: true to attachShadow, two things improve:

  • Clicking a non-focusable part of the shadow tree focuses the first focusable element inside.
  • Calling host.focus() focuses the first focusable element inside the shadow root. Also :focus matches the host when an inner element has focus, so you can style :host(:focus).
JavaScript
this.attachShadow({ mode: "open", delegatesFocus: true });

In Lit, set it with a static option:

JavaScript
class SearchBox extends LitElement {
  static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };
}

Spreading LitElement.shadowRootOptions keeps mode: "open". This option also makes labels and autofocus behave better. It is a key piece of accessible components, which Accessibility Basics for Lit Components covers in depth.

tabindex and the tab order

The tab order is calculated over the whole flattened tree, so focusable elements inside shadow roots are reached with Tab in their natural order. You do not need to do anything special. Some rules:

  • Do not put tabindex="0" on the host if inner elements are already focusable. That creates two tab stops for one control.
  • tabindex="-1" on an inner element removes it from the tab order but keeps it programmatically focusable.
  • For a custom widget with no native control inside (a custom slider made from divs), put tabindex="0" on the element that handles keys, and add ARIA roles and key handlers.

Common mistakes

  • Reading event.target on the page and expecting the inner element. It is the host.
  • Creating new CustomEvent("x") and wondering why ancestors never hear it. Add bubbles and composed.
  • Assuming change leaves the component. It is not composed.
  • Using document.activeElement to find the focused input in a component. Use shadowRoot.activeElement.
  • Adding tabindex="0" to the host of a component that contains a button, producing a double tab stop.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is event.target for a listener on the page when a user clicks a button inside a shadow root?

    Events are retargeted at the shadow boundary, so outside listeners see the host.
  2. 2. Which flags must a CustomEvent have to reach page listeners when dispatched from inside a shadow root?

    bubbles lets it travel up the tree; composed lets it cross shadow root boundaries.
  3. 3. Which of these native events is NOT composed?

    change stays inside the shadow root, so components must re-dispatch it for page code.
  4. 4. What does delegatesFocus: true do?

    delegatesFocus makes the host behave like a focus proxy for the first focusable element in its shadow tree.

Summary

  • Events bubble out of a shadow root only if they are composed, and outside listeners see the host as target.
  • composedPath() shows the real path for open roots.
  • Custom events need bubbles: true, composed: true to travel through ancestors; use prefixed names.
  • document.activeElement is the host; shadowRoot.activeElement is the real focused element.
  • delegatesFocus: true (in Lit: shadowRootOptions) lets the host forward focus to its first focusable child.

Next: Lit Templates and Bindings