I would like to have something like:
$('#myDiv').bind('class "submission ok" added'){
alert('class "submission ok" has been added');
});
I would like to have something like:
$('#myDiv').bind('class "submission ok" added'){
alert('class "submission ok" has been added');
});
Use
trigger
to fire your own event. When ever you change class add trigger with nameJS Fiddle DEMO
Learn jQuery: Simple and easy jQuery tutorials blog
You could replace the original jQuery addClass and removeClass functions with your own that would call the original functions and then trigger a custom event. (Using a self-invoking anonymous function to contain the original function reference)
Then the rest of your code would be as simple as you'd expect.
Update:
This approach does make the assumption that the classes will only be changed via the jQuery addClass and removeClass methods. If classes are modified in other ways (such as direct manipulation of the class attribute through the DOM element) use of something like
MutationObserver
s as explained in the accepted answer here would be necessary.Also as a couple improvements to these methods:
classAdded
) or removed (classRemoved
) with the specific class passed as an argument to the callback function and only triggered if the particular class was actually added (not present previously) or removed (was present previously)Only trigger
classChanged
if any classes are actually changedWith these replacement functions you can then handle any class changed via classChanged or specific classes being added or removed by checking the argument to the callback function:
There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:
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
: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.you can use something like this:
but otherwise, no, there's no predefined function to fire an event when a class changes.
Read more about triggers here