dom / latest / globaleventhandlers / onslotchange.html /

GlobalEventHandlers.onslotchange

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The onslotchange property of the GlobalEventHandlers mixin is an event handler that processes slotchange events.

The slotchange event is fired on HTMLSlotElement instances (<slot> elements) when the node(s) contained in the slot change.

Examples

The following snippet is a slightly modified version of our slotchange example which uses onslotchange rather than adding a listener for the slotchange event.

First the code gets an array of all the <slot>s and then assigns a handler function to the onslotchange property on the template's second slot — this second slot is the one that has its contents changed in the example. Every time the element in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.

let slots = this.shadowRoot.querySelectorAll('slot');
slots[1].onslotchange = function(e) {
  let nodes = slots[1].assignedNodes();
  console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".');
};

We might alternatively handle the event at a higher level. The snippet below shows the equivalent code if the handler is assigned to onslotchange on the shadowRoot. Every time the element in any slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.

this.shadowRoot.onslotchange = function(e) {
  const nodes = e.originalTarget.assignedNodes();
  console.log(`Element in Slot "${e.originalTarget.name}" changed to "${nodes[0].outerHTML}".`);
};

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
onslotchange
97
97
93
No
83
preview
97
97
93
No
No
No

See also

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onslotchange