I need to call a function when a class has been removed from an element, I have no control over when the class is removed.
Currently I can make it work by using setTimeout, so it's something like:
function checkClassRemoval() {
if (!$('.myElement').hasClass('mySecondClass')) {
// run function
}
}
setTimeout(checkClassRemoval, 1000);
Is there a better way to catch the removal of the class than running a check every second?
You can use MutationObserver class for this. It allow to subscribe to particular DOM element changes and fire events when this change happens:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
console.log('style changed!');
});
});
var target = document.getElementById('someId');
observer.observe(target, { attributes : true, attributeFilter : ['style', 'className'] });
For support of this object please refer to canIuse.com
You can override addClass/removeClass jQuery function and extend them like this:
(function(){
var nativeMethod= jQuery.fn.addClass;
jQuery.fn.addClass = function(){
var result = nativeMethod.apply( this, arguments );
jQuery(this).trigger('cssClassChanged');
return result;
}
})();
//Your code:
$(function(){
$("#yourElement").bind('cssClassChanged', function(){
console.log("triggered")
});
});
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