How can I fire an event if a CSS class is added or changed using jQuery? Does changing of a CSS class fire the jQuery change()
event?
When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.
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.
jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
jQuery unbind() MethodThe unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs.
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.
$(function() { var button = $('.clickme') , box = $('.box') ; button.on('click', function() { box.removeClass('box'); $(document).trigger('buttonClick'); }); $(document).on('buttonClick', function() { box.text('Clicked!'); }); });
.box { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box">Hi</div> <button class="clickme">Click me</button>
More info on jQuery Triggers
IMHO the better solution is to combine two answers by @RamboNo5 and @Jason
I mean overridding addClass function and adding a custom event called cssClassChanged
// Create a closure (function(){ // Your base, I'm in it! var originalAddClassMethod = jQuery.fn.addClass; jQuery.fn.addClass = function(){ // Execute the original method. var result = originalAddClassMethod.apply( this, arguments ); // trigger a custom event jQuery(this).trigger('cssClassChanged'); // return the original result return result; } })(); // document ready function $(function(){ $("#YourExampleElementID").bind('cssClassChanged', function(){ //do stuff here }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With