How to fire event if CSS class is changed using jQuery ?
Given an HTML document with heading and button, jQuery should fire an event when the CSS class of the button changes.
Approach: In jQuery, there is no provision to trigger an event on class change. An alternative method is to manually raise an event when you programmatically change the class using the trigger() function. The trigger() function will raise an event whenever the class of the button is changed.
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <script src= </script> <style> .buttonstyle { background-color: #4CB96B; color: white; } .buttonsize { padding: 1em; height: 70px; width: 400px; border: .5px solid black; outline: none; font-size: large; border-radius: 10px; } </style> </head> <body> <center> <h1> Click the button to change its style </h1> <button id="classchange-btn" class="buttonsize"> Click Me </button> </center> <script> $("#classchange-btn").click(function () { $(this).toggleClass("buttonstyle") .trigger('classChanged'); }); $("#classchange-btn").on( "classChanged", function () { alert("Button Style Change event fired"); }); </script> </body> </html> |
Output:

Initially the page looked like the following image.
On clicking the button, an alert message pops up indicating that the listener was fired and the CSS class of the button has changed.
After closing the popup, the button’s CSS class changed (notice the green background color and white text).
Recommended Posts:
- How to fire an event on file select using jQuery ?
- How to get the class of a element which has fired an event using JavaScript/JQuery?
- jQuery callbacks.fire() Method
- JQuery | Detect a textbox content is changed or not
- How to find the parent class name with known class in jQuery ?
- How to Remove an Event Handler using jQuery ?
- jQuery | event.preventDefault() Method
- jQuery | event.namespace Property
- jQuery event.metaKey Property
- How to unbind “hover” event using JQuery?
- jQuery | event.stopImmediatePropagation() Method
- jQuery | event.stopPropagation() Method
- jQuery | Selectors and Event Methods
- jQuery | event.isImmediatePropagationStopped() Method
- jQuery | Autocomplete Selection Event
- jQuery | event.timeStamp property with Example
- jQuery | event.isPropagationStopped() Method
- jQuery | event.target Property with Example
- jQuery | event.currentTarget Property
- jQuery | event.delegateTarget Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



