8

I have a jQuery script that shows an animated counter on page, but the script starts on page load, and I need it to be loaded when the user scrolls down to a specific <div>.

<script>
         $({countNum: $('#counter').text()}).animate({countNum: 63  }, {
          duration: 3000,
          easing:'linear',
          step: function() {
            $('#counter').text(Math.floor(this.countNum));
          },
          complete: function() {
            $('#counter').text(this.countNum);

          }
        });
</script>

This script need to be executed when I scroll to this specific <div> on a page.

<div id="counter"></div>
Mike Schwartz
  • 2,084
  • 1
  • 15
  • 26
Sinisa O'neill
  • 83
  • 1
  • 1
  • 4

3 Answers3

7

Working Demo: http://jsfiddle.net/fedmich/P69sL/

Try this, add your code on the start_count... then make sure to add a boolean to run your code only once.

$(function() {
    var oTop = $('#counter').offset().top - window.innerHeight;
    $(window).scroll(function(){

        var pTop = $('body').scrollTop();
        console.log( pTop + ' - ' + oTop );   //just for your debugging
        if( pTop > oTop ){
            start_count();
        }
    });
});

function start_count(){
    alert('start_count');
    //Add your code here
}
fedmich
  • 5,243
  • 3
  • 35
  • 52
3

Try this:

var eventFired = false,
    objectPositionTop = $('#counter').offset().top;

$(window).on('scroll', function() {

 var currentPosition = $(document).scrollTop();
 if (currentPosition > objectPositionTop && eventFired === false) {
   eventFired = true;
   // your code
 }

});
Paul Rad
  • 4,634
  • 1
  • 19
  • 20
1

try this:

var div_top = $('#counter').offset().top;
$(window).scroll(function(){
 if($(window).scrollTop() > div_top){
     $({countNum: $('#counter').text()}).animate({countNum: 63  }, {
      duration: 3000,
      easing:'linear',
      step: function() {
        $('#counter').text(Math.floor(this.countNum));
      },
      complete: function() {
        $('#counter').text(this.countNum);

      }
    });
 }
});

it checks how far the div is (in px) from the top and how far you scrolled. and this gets cheched every time you scroll

Rickert
  • 1,597
  • 1
  • 15
  • 23
  • 1
    Think long and hard before using functionality like this on your site. Scrolling is a common behavior. Do you really want code doing calculations/fetching data from the DOM executing every time the user scrolls? – Justin Niessner Feb 21 '14 at 13:32
  • you mean i beter could put the element to a var out of the scroll function? – Rickert Feb 21 '14 at 13:34
  • Thnak you, worked for me. I just needed to add boolean to be executed just once. :) – Sinisa O'neill Feb 21 '14 at 14:06