prc
prc

Reputation: 187

How to observe adding class to div

In my div I want to observe his class, so when this class passed is added to my div, I execute some js function.

Initial div : <div id="1" class="allow"></div>

after adding a new class : <div id="1" class="allow passed"></div>

my function to execute :

function fill() {
        jQuery('#check').show();
        jQuery('#check-val').hide();
    }

Upvotes: 1

Views: 3836

Answers (1)

Truextacy
Truextacy

Reputation: 562

You could also use a mutation observer on that div to detect when a class is added. Notice the usage of mutation observers.. https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

    var observer = new MutationObserver(function(mutations) {
       mutations.forEach(function(mutation) {
         if (mutation.attributeName === "class") {
            if ($(mutation.target).hasClass('passed')){
                    alert("passed class was added");
                    fill();
           }
         }
     });
  });

observer.observe(document.getElementById('1'), {
  attributes: true
});

Here is a jsfiddle https://jsfiddle.net/e37am2hq/

Upvotes: 3

Related Questions