Web components slotchange event question

hi there

I’ve been doing some work with web components and elm. I’ve had some success but I’ve ran into a bit of a hurdle.

I’d like to use the slot feature of a web component as part of it’s API. There’s a useful event called slotchange but I can not figure out how to get it to fire. It only fires if I add/remove (replace) a slot DOM Node. This is easy enough to do in Javascript, but with Elm managing the DOM I can not figure out how to do it in Elm.

I thought about trying the Html.Keyed but if I understand correctly what that does, is it’s all about making fewer DOM changes not more.

If you’re not sure exactly what I’m talking about I made an example to try to isolate this issue as much as I could. I’m not sure how much the code “speaks for it self” though, so I’d be happy to supply any additional details.

Anyone have any advice?

Looking at the MDN docs for the slotchange event there is this note

Note: the slotchange event doesn’t fire if the children of a slotted node change — only if you change (e.g. add or delete) the actual nodes themselves.

It should be sufficient to use Html.Keyed and just use a different key when you want the event to be fired. The event isn’t fired because Elm’s VDOM recycyles DOM nodes where it can.

EDIT the referenced example causes a slotchange by removing the slot attribute and attaching it again, if that is any help :slight_smile: web-components-examples/slotchange/main.js at main · mdn/web-components-examples · GitHub

1 Like

Thanks so much. Using Html.Keyed totally worked. I updated my example in case any one else has the same issue they can see a solution. Now to try to apply this to my real problem. :slightly_smiling_face:

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.