1

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();
    }
prc
  • 187
  • 2
  • 14

1 Answers1

3

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/

Truextacy
  • 562
  • 1
  • 5
  • 26
  • It is possible to check exactly this added class `passed` – prc May 30 '18 at 17:40
  • I modified my answer, and the jsfiddle. Is that what you mean? – Truextacy May 30 '18 at 17:48
  • Use jQuery hasClass function. Above function may fail if passed is not at last. – Dnyaneshwar Supe May 30 '18 at 17:51
  • Just approved your edit @DnyaneshwarSupe. `hasClass()` is cleaner. and yeah, `.passed` would have needed to be the last class in the list. – Truextacy May 30 '18 at 17:53
  • @Austin Truex, sorry but no, in your `setTimeout(function() { $("#1").addClass('passed'); }, 3000)` if I replace ``addClass('passed');` to `addClass('no-passed');` it still detecte it – prc May 31 '18 at 10:51
  • How did you run it? The `hasClass()` just checks to see if that element has the class passed.. if the class is already there, it will return true. You could also use my original method which is posted in the jsfiddle, however that method requires that `.passed` is the last class in the class list – Truextacy May 31 '18 at 15:15