Matoeil Matoeil - 4 years ago 9430
Javascript Question

how to fire event on class change using jquery?

I would like to have something like:

$('#myDiv').bind('class "submission ok" added'){
alert('class "submission ok" has been added');
});

Answer Source

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});

UPDATE

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

var $div = $("#foo");
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.attributeName === "class") {
            var attributeValue = $(mutation.target).prop(mutation.attributeName);
            console.log("Class attribute changed to:", attributeValue);
        }
    });
});    
observer.observe($div[0],  {
    attributes: true
});

$div.addClass('red');

Example fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download