Home » Javascript » Run animations only when in viewport

Run animations only when in viewport

Posted by: admin August 19, 2018 Leave a comment


I have a site stuffed with lots of ongoing (looped) javascript-animations, which I want to be running only when they show up in the viewport in order to save performance.

Is there any cheap trick for achieving this? ideas on how to save performance in this particular case are very welcome.

I tried it like this, but doesn’t work. Probably because the function isn’t being triggered when triggerEffect turns true:

var triggerEffect = false;


  var wScroll = $(window).scrollTop(),
      divTop = $('#effect-div').offset().top-$(window).height(),
      divBottom = $('#effect-div').offset().top+$('#effect-div').height();

  if (wScroll > divTop && wScroll < divBottom) {
    triggerEffect = true;
  } else {
    triggerEffect = false;


$(document).ready(function loop() {
  setTimeout( function () {
    $("#effect-div").css("background-color", "blue")

    setTimeout(function () {
      $("#effect-div").css("background-color", "red")
    }, 200);
    if ( triggerEffect == true ) {

  }, 400);


for the full code (including html and css) check this out on CODEPEN