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>
0

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

Comments

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
 }

});

Comments

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

3 Comments

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?
you mean i beter could put the element to a var out of the scroll function?
Thnak you, worked for me. I just needed to add boolean to be executed just once. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.