0

I'm trying to understand whether there's a way to register an event whenever an element's class has been changed.

I afraid of using setInterval for a check cause it might cause the browser to stuck.

Thanks.

user1326293
  • 923
  • 2
  • 9
  • 24
  • hmm, dynamically you are going to change `class`, so call event into the same method. I don't see reason – Maxim Shoustin May 07 '13 at 14:07
  • No, there is no "onclasschange" event. Why do you want to do that? What are you trying to do? A better method would be to call a function *yourself* when the class changes (like, add a new line of code each time you change the class). – gen_Eric May 07 '13 at 14:08
  • 1
    Asked before: http://stackoverflow.com/questions/1950038/jquery-fire-event-if-css-class-changed – Pete May 07 '13 at 14:08
  • And http://stackoverflow.com/questions/7684968/javascript-bind-an-event-to-a-change-of-classname – Justin Helgerson May 07 '13 at 14:08
  • You could define setter for the class property – Michael Sazonov May 07 '13 at 14:11

2 Answers2

1

If you are using jQuery. This could be a solution:

https://github.com/aheckmann/jquery.hook/blob/master/jquery.hook.js

I wouldn't recommend overwriting methods that you don't own but it is possible to do something like this:

//Overide addClass Method
 (function(){

    var addClassMethod = jQuery.fn.addClass;

    jQuery.fn.addClass = function(){
        var result = addClassMethod.apply( this, arguments );
        jQuery(this).trigger('classChanged');
        return result;
    }

})();


$(".yourElemClass").bind('classChanged', function(){ 
    //Your code goes here     
});
Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
0

One thing you could do is create a changeClass function :

function changeClass(element, className) {
     element.className = className;
     // Your code to run on the class change
}

Then, when you need to change the class of an element just :

changeClass(myElement, "myClass");
nialna2
  • 2,056
  • 2
  • 25
  • 33