Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire an 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'); }); 
like image 775
Matoeil Avatar asked Oct 16 '13 10:10

Matoeil


People also ask

What is use of change event in jQuery?

The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected.

How do you target a class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


1 Answers

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) {     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/2.1.1/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.

like image 78
Rory McCrossan Avatar answered Sep 22 '22 06:09

Rory McCrossan