Listen for change of class in jquery
Here are some other finds that might provide a solution:
- Most efficient method of detecting/monitoring DOM changes?
- How can I detect when an HTML element’s class changes?
- Monitoring DOM Changes in JQuery
And as it was suggested in #2, why not make current
a class that is added, rather than a ID, and have the following CSS handle the show/hide action.
<style type='text/css>
.current{display:inline;}
.notCurrent{display:none;}
</style>
Might also be worth it to look into .on() in jquery.
I know this is old, but the accepted answer uses DOMSubtreeModified
, which has now been deprecated for the MutationObserver
. Here's an example using jQuery (test it out here):
// Select the node that will be observed for mutations
let targetNode = $('#some-id');
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: false, subtree: false, attributeFilter: ['class'] };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.attributeName === "class") {
var classList = mutation.target.className;
// Do something here with class you're expecting
if(/red/.exec(classList).length > 0) {
console.log('Found match');
}
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode[0], config);
// Later, you can stop observing
observer.disconnect();
You can bind the DOMSubtreeModified
event. I add an example here:
$(document).ready(function() {
$('#changeClass').click(function() {
$('#mutable').addClass("red");
});
$('#mutable').bind('DOMSubtreeModified', function(e) {
alert('class changed');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mutable" style="width:50px;height:50px;">sjdfhksfh
<div>
<div>
<button id="changeClass">Change Class</button>
</div>
http://jsfiddle.net/hnCxK/13/