Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect class removal by code I have no control over

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?

like image 394
prettyInPink Avatar asked Dec 18 '22 09:12

prettyInPink


2 Answers

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

like image 117
VadimB Avatar answered Dec 31 '22 12:12

VadimB


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")
    });
});
like image 37
Nedim Hozić Avatar answered Dec 31 '22 13:12

Nedim Hozić