A
A
Anya Ivanova2020-04-28 12:42:05
JavaScript
Anya Ivanova, 2020-04-28 12:42:05

How to track the appearance of a class and set a condition in MutationObserver?

I have a slider. When a slide appears, the active class appears. I want to track this occurrence. I found MutationObserver, but I don’t know how to correctly set the condition that if an active class appears at a certain id, then such and such code is executed (in my case, the block with id="b1" is visible). If another slide has appeared, then another block has also appeared, and other blocks are not active.
I would be very grateful if you can help somehow.

<div class="carousel-item active" id="#b-1049"></div>
  <div class="carousel-item" id="#b-1050"></div>
  <div class="carousel-item" id="#b-1051"></div>

<div id="b1">Один</div> 
<div id="b2">Два</div> 
<div id="b3">Три</div>


let variable1 = document.querySelector("#b-1049").getAttribute("class");
        let variable2 = document.querySelector("#b-1050").getAttribute("class");
        let variable3 = document.querySelector("##b-1051").getAttribute("class");
        let er =  document.getElementById("b1");
        let qw =  document.getElementById("b2");
        let ro =  document.getElementById("b3");

  let observer = new MutationObserver(function(mutations) {
              if (mutations.type === 'childList') {
                    if (variable1 == "carousel-item active") {
                        er.style.display = "block";
                        qw.style.display = "none";
                        ro.style.display = "none";
                    }
                }
        });

        observer.observe(variable2, {
            attributes: true,
            childList: true
        });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2020-04-28
@saharok13

let observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(e) {
    if (e.type == "attributes" && e.attributeName == "class") {
      if (e.oldValue.indexOf("active") == -1 && e.target.classList.contains("active")) {
      console.log("Класс active добавлен к элементу с ID:#"+e.target.id);
      }      
      if (e.oldValue.indexOf("active") != -1 && !e.target.classList.contains("active")) {
      console.log("Класс active убран с элемента с ID:#"+e.target.id);
      }
    }
  });

});

observer.observe(document.querySelector("#myelem"), {
  attributes: true,
  attributeOldValue: true
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question