Search code examples
javascriptjquerysetintervalvar

Add 1 to variable if opacity is == 1 within a setInterval


I have a variable that I need to add 1 to each time an elements opacity is 1. I need to keep checking the opacity so I have wrapped it in a setInterval.

I am wondering if there is a way to only add 1 to the variable each time the opacity changes to 1 instead of keep adding 1 over and over again because of the interval. Here is my code

var number = 1;

var intervalsizer = setInterval(function() {
  if ($(".cardButtons__discuss").css('opacity') == 1) {
    number++;
    console.log(number)
  }

  function fooo() {
    if (number == 1) {
      //do something
    }
    if (number == 2) {
    }
    if (number == 3) {
      //do something
    }
    if (number == 4) {
      //do something
    }
  }
}, 50);

Thanks in advance


Solution

  • Tracking an attribute can be done using a MutationObserver. This code tracks all attribute changes on the element and filters out changes to the style and class attributes specifically. When the attributes change it looks if the opacity value has changed.

    This solution only works if the opacity is changed on the element itself, by setting a class or by setting a style.

    const mydiv = document.getElementById('mydiv')
    
    const observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        if(mutation.attributeName !== 'style' && mutation.attributeName !== 'class') return;
        const target = $(mutation.target);
        const oldVal = target.data("oldOpacity");
        const newVal = getComputedStyle(target[0]).opacity;
        if(oldVal != newVal) {
          console.log(`opacity changed. Old: ${oldVal}, New: ${newVal}`)
          target.data("oldOpacity", newVal)
        }
      });    
    });
    
    const config = { 
      attributes: true 
    };
     
    observer.observe(mydiv, config);
    
    
    //code to change the opacity and another style attribute.
    let i = 0;
    setInterval(() => {
      switch (i % 4) {
        case 0:
          mydiv.style.backgroundColor = "red"
          break
        case 1:
          mydiv.style.opacity = "0.5"
          break
        case 2:
          mydiv.classList.add('blue')
          break
        case 3:
          mydiv.style.opacity = ""
          mydiv.classList.remove('blue')
          mydiv.style.backgroundColor = "blue"
          break;
      }
      i++;
    }, 1000)
    .blue {
      background-color: blue !important;
      opacity: 1 !important;
    }
    
    #mydiv {
      background-color: red;
      width: 100px;
      height: 100px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="mydiv"></div>