I'd like my event to be triggered when a div tag containing a trigger class is changed.
I have no idea how to make it listen to the class' adding event.
<div id="test">test</div> <script type="text/javascript"> document.getElementById.setAttribute("class", "trigger"); function workOnClassAdd() { alert("I'm triggered"); } </script>
To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.
To listen to class change we need to instantiate the MutationObserver object, pass the callback function, and call the observe() method. The observe() method accepts two arguments the target node and options object which should contain attributes property that is set to true.
The future is here, and you can use the MutationObserver interface to watch for a specific class change.
let targetNode = document.getElementById('test') function workOnClassAdd() { alert("I'm triggered when the class is added") } function workOnClassRemoval() { alert("I'm triggered when the class is removed") } // watch for a specific class change let classWatcher = new ClassWatcher(targetNode, 'trigger', workOnClassAdd, workOnClassRemoval) // tests: targetNode.classList.add('trigger') // triggers workOnClassAdd callback targetNode.classList.add('trigger') // won't trigger (class is already exist) targetNode.classList.add('another-class') // won't trigger (class is not watched) targetNode.classList.remove('trigger') // triggers workOnClassRemoval callback targetNode.classList.remove('trigger') // won't trigger (class was already removed) targetNode.setAttribute('disabled', true) // won't trigger (the class is unchanged)
I wrapped MutationObserver with a simple class:
class ClassWatcher { constructor(targetNode, classToWatch, classAddedCallback, classRemovedCallback) { this.targetNode = targetNode this.classToWatch = classToWatch this.classAddedCallback = classAddedCallback this.classRemovedCallback = classRemovedCallback this.observer = null this.lastClassState = targetNode.classList.contains(this.classToWatch) this.init() } init() { this.observer = new MutationObserver(this.mutationCallback) this.observe() } observe() { this.observer.observe(this.targetNode, { attributes: true }) } disconnect() { this.observer.disconnect() } mutationCallback = mutationsList => { for(let mutation of mutationsList) { if (mutation.type === 'attributes' && mutation.attributeName === 'class') { let currentClassState = mutation.target.classList.contains(this.classToWatch) if(this.lastClassState !== currentClassState) { this.lastClassState = currentClassState if(currentClassState) { this.classAddedCallback() } else { this.classRemovedCallback() } } } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With