views:

1373

answers:

3

Hello,

how could I fire a event if the a css class was added or changed qith jQuery? Does changing of css class fire the jQuery change() event?

+2  A: 

change() does not fire when a CSS class is added or removed or the definition changes. It fires in circumstances like when a select box value is selected or unselected.

I'm not sure if you mean if the CSS class definition is changed (which can be done programmatically but is tedious and not generally recommended) or if a class is added or removed to an element. There is no way to reliably capture this happening in either case.

You could of course create your own event for this but this can only be described as advisory. It won't capture code that isn't yours doing it.

Alternatively you could override/replace the addClass() (etc) methods in jQuery but this won't capture when it's done via vanilla Javascript (although I guess you could replace those methods too).

cletus
+10  A: 

Whenever you change a class in your script, you could use a trigger to raise your own event.

$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged')
....
$(otherSelector).bind('cssClassChanged', data, function(){ do stuff });

but otherwise, no, there's no baked-in way to fire an event when a class changes. change() only fires after focus leaves an input whose input has been altered.

More info on jQuery Triggers

Jason
What's the deal with triggering the event which then calls a function? Why not call the function directly, instead of triggering it?
RamboNo5
Triggering is a mechanism that will allow certain elements to "subscribe" to an event. that way, when the event is triggered, those events can all happen at once and run their respective functionality. for instance, if i have one object that changes from red to blue and three objects waiting for it to change, when it changes, i can just trigger the `changeColor` event, and all those objects subscribing to that event can react accordingly.
Jason
+5  A: 

I would suggest you override the addClass function. You can do it this way:

// Create a closure
(function(){
    // Your base, I'm in it!
    var originalAddClassMethod = jQuery.fn.addClass;

    jQuery.fn.addClass = function(){
        // Execute the original method.
        originalAddClassMethod.apply( this, arguments );

        // call your function
        // this gets called everytime you use the addClass method
        myfunction();

    }
})();

// document ready function
$(function(){
    // do stuff
});
RamboNo5
Combining this with Jason's $(mySelector).trigger('cssClassChanged') would be the best approach I think.
kosoant