home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Trigger An Action When Something Changes A Web Component's Content Externally

May 2024

I'm working on a code block with auto copy web component 1 for my color picker 2. The content needs to be able to be updated from external javascript. It's possible to use slots and simply have the content update, but I'm running a process to add line numbers so I need an alternative.

The approach I'm using here is to have a mutation observer to watch for changes and then trigger an update.

For this example, the button is outside the web component. It updates the custom element's span which is what's being observed by the component's code. When a change happens, the value of the span is used to generate a new value that's then output into the shadowRoot.

Here's a live example:

Original Text

The mutation observer fires once when things are set up. That threw me off a little. I was expecting things wouldn't change by the point the observer is started. That feels like it may be a race condition. Something to look into there.

Using slots directly is probably the way to go if it works for the use case. This is working nicely for the updates that as far as I can tell slots don't cover without more work.

═══ § ═══

Endnotes

Footnotes And References