Home » Jquery » javascript – MutationObserver – how to listen to class changes of a certain element?

javascript – MutationObserver – how to listen to class changes of a certain element?

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a slider and want to fire an event depending on which slide is active. Since the slider itself is out of my control, I’m going for a mutationObserver solution with listening to class changes on the slides.

This is what I have so far, but it’s not even getting to the console.log part. What could be the issue? It throws no errors, it just doesn’t work.

jQuery(document).ready(function($) {
  var $slides = $("#hero-slider .swiper-slide");

  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.attributeName === "class") {
        console.log('mutationobs worked');

        if (($('#hero-slider .swiper-slide.swiper-slide-active').attr('data-swiper-slide-index') == 0) || ($('#hero-slider .swiper-slide.swiper-slide-duplicate-active').attr('data-swiper-slide-index') == 0)) {
          $('#landing-hero .elementor-shape').css('z-index', '0');
        } else if (($('#hero-slider .swiper-slide.swiper-slide-active').attr('data-swiper-slide-index') == 1) || ($('#hero-slider .swiper-slide.swiper-slide-duplicate-active').attr('data-swiper-slide-index') == 1)) {
          $('#landing-hero .elementor-shape').css('z-index', '5');
        }
      }
    });
  });

  observer.observe($slides[0], {
    attributes: true
  });
});
How to&Answer: