Listen for class change in JavaScript
There isn’t an event for class list changes, but you can write a function that listens for class changes on an element with the MutationObserver API.
Copy & paste:
function onClassChange(node, callback) {
let lastClassString = node.classList.toString();
const mutationObserver = new MutationObserver((mutationList) => {
for (const item of mutationList) {
if (item.attributeName === "class") {
const classString = node.classList.toString();
if (classString !== lastClassString) {
callback(mutationObserver);
lastClassString = classString;
break;
}
}
}
});
mutationObserver.observe(node, { attributes: true });
return mutationObserver;
}
Step by step:
- The function accepts two parameters: a reference to a DOM node to watch and the callback to execute when the class has changed.
- Within the function, we store a reference to the class list as a string that we will use for comparison later.
- Create a new
MutationObserver
instance with a callback that listens for class changes.- Inside that callback, we loop through the mutation list and look for any
changes to the
class
attribute. - If we find one, then we compare the current class list as a string to the
reference declared above.
- This comparison is necessary to prevent false class change positives, e.g adding the same class twice.
- If the class strings do not match, invoke the callback and update the class string reference.
- Break out of the loop if we have detected a change.
- Inside that callback, we loop through the mutation list and look for any
changes to the
- Observe the passed node with the new mutation observer instance and configure it to fire on attribute changes.
- Return the mutation observer for later clean up
Try it out:
See the Pen Function to listen for class change by Sean McPherson (@SeanMcP) on CodePen.
Takeaway: It would be nice if there was a standard method for listening to
class changes, but it is nice to know that you can write your own with a
MutationObserver
.
Read more:
- https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
- https://www.seanmcp.com/articles/event-listener-for-class-change/