Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class name change Event in jQuery

Is there a way to trigger a event in jQuery when an elements classes are changed?

Examples:

<img class="selected" />

into

<img class="selected newclass" />

triggers an event


And

<img class="selected" />

into

<img class="" />

trigger an event

like image 252
Andreas Avatar asked Jun 29 '10 10:06

Andreas


People also ask

How to get change event in jQuery?

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. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.

How do you listen to a class change?

To listen to class change we need to instantiate the MutationObserver object, pass the callback function, and call the observe() method. The observe() method accepts two arguments the target node and options object which should contain attributes property that is set to true.

What is toggleClass?

Definition and Usage. The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.


1 Answers

You might be able to workaround on a little hacky way. Hook .addClass() & .removeClass() like so:

var _addClass    = $.fn.addClass,
    _removeClass = $.fn.removeClass;

$.fn.addClass    = function(){
    // do whatever here
    return _addClass.apply(this, arguments);
}

$.fn.removeClass = function(){
    // do whatever here
    return _removeClass.apply(this, arguments);
}

That way, assuming you are just interested in watching elements class changes with jQuery, you can trigger whatever code on adding or removing classes. Again, just if you are using jQuery, for this example.

Of course, you can hook and overwrite any javascript function that way.

As Nick Craver mentioned in a comment, there are several other jQuery methods which can add or remove an elements class. You would have to hook all of those, namely:

.addClass()
.removeClass()
.toggleClass()
.removeAttr('class')
.attr('class', 'changed')

unless you know exactly which methods are called to manipulate a class, you would have to care about all of those.

like image 167
jAndy Avatar answered Oct 14 '22 04:10

jAndy