# Bubbling in Shadow DOM

[Web Components](https://lochiwei.gitbook.io/web/component) ⟩ [Shadow DOM](https://lochiwei.gitbook.io/web/component/shadow-dom) ⟩ [Events](https://lochiwei.gitbook.io/web/component/shadow-dom/events) ⟩

{% tabs %}
{% tab title="📗 參考" %}

* JS.info ⟩ [Bubbling, event.composedPath()](https://javascript.info/shadow-dom-events#bubbling-event-composedpath)&#x20;
  {% endtab %}

{% tab title="📘 手冊" %}

* [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) ⟩
  * [composedPath()](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath) : [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget)\[ ]
  * [composed](https://developer.mozilla.org/en-US/docs/Web/API/Event/composed) : boolean
* [element.tagName](https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName): string
  {% endtab %}

{% tab title="👥 相關" %}

* [custom](https://lochiwei.gitbook.io/web/browser/event/custom "mention")
  {% endtab %}
  {% endtabs %}

{% hint style="info" %}

* If **event** occurs on an element from **shadow DOM**, then, as it bubbles out of shadow DOM, its **`event.target`** is **reset** to **`<custom-element>`**.
* For purposes of **event bubbling**, [**flattened DOM**](https://lochiwei.gitbook.io/web/component/slots#flattened-dom) is used.
* if we have a **slotted element**, and an **event** occurs somewhere **inside** it, then it bubbles up to the **`<slot>`** and upwards. 👉 see: tab 1️⃣ (click on slotted element)
  {% endhint %}

## event.composedPath() <a href="#composedpath" id="composedpath"></a>

{% hint style="info" %}

* The full path to the original event target, with all the shadow elements, can be obtained using **`event.composedPath()`** 👉 see: tab 1️⃣
  {% endhint %}

{% tabs %}
{% tab title="1️⃣" %}
💾 [replit](https://replit.com/@pegasusroe/eventcomposedPath#UserCard.js) (live demo on [codepen](https://codepen.io/lochiwei/pen/jOwxqQo))

{% embed url="<https://codepen.io/lochiwei/pen/jOwxqQo>" %}
{% endtab %}

{% tab title="result" %}

* click on "Name:" label:

```
inner target: <B>
[composed path]:
b, div, ShadowRoot, user-card, body, html, HTMLDocument, Window
-------------------------
outer target: <USER-CARD>
```

* click on "John Smith" (the slotted element)

```
inner target: <SPAN>
[composed path]:
span, slot, div, ShadowRoot, user-card, body, html, HTMLDocument, Window
-------------------------
outer target: <SPAN>
```

{% hint style="warning" %}
If the shadow tree was created with **`{mode: 'closed'}`**, then the **composed path** starts from the **host**: **\<user-card>** and upwards.
{% endhint %}
{% endtab %}
{% endtabs %}

## Topics

* [Events that Cross Shadow DOM Boundary](https://lochiwei.gitbook.io/web/component/shadow-dom/events/composed)
