The HTML onslotchange event
The HTML onslotchange attribute runs JavaScript when the nodes assigned to a <slot> in a web component change. It is an inline handler for the slotchange event; in modern code prefer addEventListener('slotchange', …).
Overview
The onslotchange event attribute runs JavaScript when a slot's assigned content changes. In JavaScript the event itself is named slotchange. Drop the on prefix when you call addEventListener.
It is fired on the <slot> element itself, inside a shadow root, whenever the nodes assigned to that slot change.
You can wire this up with the inline onslotchange HTML attribute, but the modern, recommended approach is element.addEventListener('slotchange', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element onslotchange="handler()">…</element>
element.addEventListener('slotchange', handler);
Best practices
- Prefer
element.addEventListener('slotchange', handler)over the inlineonslotchangeattribute; it separates behavior from markup and allows multiple handlers. - Attach these on
windowwithaddEventListenerrather than as <body> attributes. - Keep these handlers fast; they run at moments that affect the whole page.
- Remove listeners you no longer need to avoid leaks in long-lived pages.
Frequently asked questions
What is the onslotchange event?
slotchange.Where do I attach this event?
<slot> element itself, usually from the custom element's own code.Can I use it as a body attribute?
slotchange fires on the <slot> inside a shadow root and does not escape it, so attach it with slot.addEventListener from the component's own code.Should I use the onslotchange attribute or addEventListener?
element.addEventListener('slotchange', …) in JavaScript. The inline onslotchange attribute works but mixes behavior into the markup and allows only one handler per element.