0

I have written code below and basically grabs the element that is a scroll slide on a e-commerce website that changes its inline style attribute transform property every few second to slide the slideshow of images from left to right.

I want to observe the mutation change but only fire console.log (1 time) when it detects style attribute transform property change but I have problem. It is firing 40 - 50 times as the scroll slide change transform translate in x direction every 100 or pixels so mutation observer detects the change as 40 - 50 changes

how do i solve this issue of only having output console.log once and not 40-50 times. The scroll slide is also doing it continuously after page load every few seconds too.

  var styleMutate = function(mutations, observer) {
    mutations.forEach(function(mutationRecord) {
      if(mutationRecord.attributeName === 'style') { 
        //fireGaEvent('Image gallery scrolls to the right');
        console.log("style change");
        console.log(mutationRecord);
      }
      observer.disconnect();
    });
  };

  var observer = new MutationObserver(styleMutate);

  var target = document.getElementsByClassName('touchcarousel-container')[0];
  observer.observe(target, { attributes : true, attributeFilter : ['style']});
  • If it fires multiple times, that means the style property is *not* set only once every few seconds, but actually the animation is controlled by JS and it does set it every frame. You can [debounce](https://stackoverflow.com/q/24004791/1048572) your console.log statement. – Bergi Dec 08 '21 at 21:34
  • Thank you. That worked! – Muhammad Shahroze Dec 09 '21 at 22:09

0 Answers0