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 ...

Get Modern Front-End Development for Rails now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.