@saharok13
начинающий программист

Как отследить появление класса и поставить условие в MutationObserver?

У меня стоит слайдер. Когда появляется слайд, то появляется класс active. Я хочу отследить это появление. Нашла MutationObserver, но не знаю как правильно поставить условие, что если появляется класс active у определенного id, то выполняется такой-то код( в моем случае блок с id="b1" виден). Если другой слайд появился, то другой блок тоже появился, а другие блоки не активны.
Буду очень благодарна, если как-нибудь поможете.
<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
        });
  • Вопрос задан
  • 91 просмотр
Решения вопроса 1
twobomb
@twobomb
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
});
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы