Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript How to play an animation when an element isOnScreen() only once? Reply To: How to play an animation when an element isOnScreen() only once?

#152160
TheDoc
Member

You should be able to do this:

$(document).scroll(function(event) {

  var result = $('.footer').isOnScreen();
  var hasBeenSeen = false;

  if(result && !hasBeenSeen) {

    hasBeenSeen = true;

    jQuery(function($) {
      $('.timer').countTo({
        from: 0,
        to: 1975,
        speed: 2000,
        refreshInterval: 50,
        onComplete: function(value) {
          console.debug(this);
        }
      });
    });

    jQuery(function($) {
      $('.timer-twee').countTo({
        from: 0,
        to: 500,
        speed: 2000,
        refreshInterval: 50,
        onComplete: function(value) {
          console.debug(this);
        }
      });
    });
  }
});

Note that you don’t need to do result == true because result itself will either be true or false, so you can just do if( result ).

All I’m doing in my code is providing a second var to check. When the page loads it’s false and once your function runs once it becomes true. Your timer functions are only allowed to run if hasBeenSeen is false so they’ll only run once.

I haven’t actually tested this code but it should work just fine.