Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start executing jQuery function when I scroll to a specific <div> [duplicate]

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>
like image 868
Sinisa O'neill Avatar asked Feb 21 '14 13:02

Sinisa O'neill


2 Answers

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
}
like image 123
fedmich Avatar answered Oct 12 '22 22:10

fedmich


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
 }

});
like image 39
Paul Rad Avatar answered Oct 12 '22 23:10

Paul Rad