简体   繁体   中英

Run animations only when in viewport

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;

$(window).scroll(function(){

  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 ) {
      loop();
    };

  }, 400);

});

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

I think you should move the scroll function inside the document ready function, so in the end it should look like this:

  var triggerEffect = false; jQuery(document).ready(function(){ jQuery(window).scroll(function(){ var wScroll = $(window).scrollTop(), divTop = $('#effect-div').offset().top-$(window).height() / 1.2, divBottom = $('#effect-div').offset().top+$('#effect-div').height() / 1.2; console.log("wScroll "+wScroll); console.log("divTop "+divTop); console.log("divBottom "+divBottom); if (wScroll > divTop && wScroll < divBottom) { triggerEffect = true; loop(); } else { triggerEffect = false; } console.log("triggerEffectSCROLL "+triggerEffect); }); }); function loop() { console.log("triggerEffectLOOP "+triggerEffect); setTimeout( function () { jQuery("#effect-div").css("background-color", "blue") setTimeout(function () { jQuery("#effect-div").css("background-color", "red") }, 200); if ( triggerEffect == true ) { loop(); }; }, 400); } 
  body { height: 3000px; } #effect-div { height: 300px; width: 500px; background-color: red; margin-top: 1000px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="effect-div"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM