Skip to content Skip to sidebar Skip to footer

How To Turn Off Js/css Background Effect On Scroll?

I love cool JS/CSS background effects, but on many slower devices they take up a lot of CPU usage and really bog down the browser. A really good example is this site: http://volar.

Solution 1:

You can remove the class (or id) of the div which is causing the resource drain when the div leaves the viewport (ie the screen). You can even add a temporary class while it is off the screen if you wish.

Take a look at the code snippet below. Although you can't see it, the green box loses the class green when it goes off the screen, and gets the class orange added to it instead (inspect the element to see it change). Then when it comes back onto the screen the div gets the class green and loses the class orange:

functionisElementInViewport(el) {
    let rect = el.getBoundingClientRect();
    return rect.bottom > 0 && rect.right > 0 && rect.left < (window.innerWidth || document.documentElement.clientWidth) && rect.top < (window.innerHeight || document.documentElement.clientHeight);
}

let isVisible = true;

window.onscroll = function() {
  let myGreenBox = document.getElementById('green-box');
  if(!isElementInViewport(myGreenBox) && isVisible) {
    myGreenBox.classList.add("orange");
    myGreenBox.classList.remove("green");
    
    console.log("Green Box style removed");
    isVisible = false;
  } elseif(isElementInViewport(myGreenBox) && !isVisible){
    myGreenBox.classList.add("green");
    myGreenBox.classList.remove("orange");
    console.log("Green Box style added");
    isVisible = true;
  }
  
};
.box {
  height: 100px;
  width: 100px;
}

.green {
  background-color: lime;
}

.orange {
  background-color: orange;
}

.container {
  height: 200vh;
}
<divclass="container"><divid="green-box"class="box green"></div></div>

You can apply this idea to <div id="fss" class="fss full-screen "></div> to 'disable' it when it is off the screen.

Post a Comment for "How To Turn Off Js/css Background Effect On Scroll?"