I would like to have something like:
$('#myDiv').bind('class "submission ok" added'){ alert('class "submission ok" has been added'); });
Advertisement
Answer
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 – 2015
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) { var attributeValue = $(mutation.target).prop(mutation.attributeName); console.log("Class attribute changed to:", attributeValue); }); }); observer.observe($div[0], { attributes: true, attributeFilter: ['class'] }); $div.addClass('red');
.red { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <div id="foo" class="bar">#foo.bar</div>
Be aware that the MutationObserver
is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.
UPDATE – 2022
Here’s an implementation of the above wrapped in to a jQuery extension method:
// extension method: $.fn.classChange = function(cb) { return $(this).each((_, el) => { new MutationObserver(mutations => { mutations.forEach(mutation => cb && cb(mutation.target, $(mutation.target).prop(mutation.attributeName))); }).observe(el, { attributes: true, attributeFilter: ['class'] // only listen for class attribute changes }); }); } // usage: const $foo = $("#foo").classChange((el, newClass) => console.log(`#${el.id} had its class updated to: ${newClass}`)); const $fizz = $("#fizz").classChange((el, newClass) => console.log(`#${el.id} had its class updated to: ${newClass}`)); // trigger $('#trigger').on('click', () => { $foo.removeClass('red'); $fizz.addClass('green dark-bg'); });
.red { color: #C00; } .green { color: #0C0; } .dark-bg { background-color: #666; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <button id="trigger">Change classes</button> <div id="foo" class="bar red">#foo.bar</div> <div id="fizz" class="buzz">#fizz.buzz</div>