Start executing the jQuery function when I go to a specific <div>

I have a jQuery script that shows an animated counter on a page, but the script starts by loading the page, and I need it to load when the user scrolls to a specific one <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 should be executed when I look at this <div>on the page.

<div id="counter"></div>
+4
source share
3 answers

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

Try this, add your code to start_count ... then be sure to add a boolean to run the 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
}
+7

:

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);

      }
    });
 }
});

, div ( px) . cheched ,

+1

Try the following:

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

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

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

});
+1
source

Source: https://habr.com/ru/post/1528110/


All Articles