JQuery fire function on element class change

I need to trigger an event when I add a certain class to a button, but I don't know how to make it listen for the class add event.

I have something like this:

<script type="text/javascript">   

$(document).ready(function() {


    $(id_element).addClass("active");

     //this function will fire on add "active" class to "id_button" element
     function fireOnActiveClass() {
        //do something
     }


} 

</script>

      

I cannot touch on the code $(id_element).addClass("active");

for several reasons.

I am currently using jQuery 1.7.2

Could you please tell me how or what I need to know?

+3


source to share


5 answers


I found a solution using this jQuery plugin: http://meetselva.github.io/attrchange/



0


source


You are modifying the class of the control in your code. So why not just call the button click on class change?



$(id_element).addClass("active");
$(id_button).click();

$(id_button).click(function () {
     if ($(this).hasClass) {
     //do something

     }
 });

      

+1


source


No event is raised when the class changes. An alternative is to manually raise the event when the class changes programmatically:

$(document).ready(function() {
    $(id_element).addClass("active").trigger('classChange');
    $(id_element).on('classChange', function() {
         // do stuff
    });
});

      

+1


source


Another way would be to call the function immediately after adding the class:

$.fn.classAdded = function() {
    var $button = $(this);
    if($button.hasClass('id_button')) {
        // ...
    }
    return $button;
}

$(id_element).addClass("active").classAdded();

      

0


source


Could this jQuery plugin be any help?

https://github.com/tormjens/jquery-dom-router

You can change the default element using $.DOMRouter.defaults.element = '#element';

before initializing the plugin.

0


source







All Articles