Skip to content
Advertisement

How to fire an event on class change using jQuery?

I would like to have something like:

JavaScript

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:

JavaScript

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:

JavaScript
JavaScript
JavaScript

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:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement