Observing and Responding to DOM Changes
If we want to use the DOM as a place to hold on to the state of the client-side system, it’s helpful to be able to know when that state changes. In a Hotwire system, where new HTML text might be added to the DOM as a result of a form submission or an ActionCable text receipt, being able to detect that HTML change and perform an action based on it allows for a lot of cool behavior, even while keeping the drawing logic on the server side.
We can do this by using the MutationObserver API, which is a standard part of every recent browser. Stimulus itself is powered by MutationObserver calls, so any browser that can run Stimulus can manage MutationObservers. Browsers that are older than, say, Internet Explorer ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access