-1

How do I fire this function only at the time when I scroll down to "myTargetElement" and it becomes visible on the screen, and not immediately after page is loaded?

<script src="countUp.min.js" type='text/javascript'></script>

<script>
$(document).ready(function() {
    var countOptions = {
        useEasing : true,
        useGrouping : true,
        separator : ',',
        decimal : '.'
    }
    var customerNumber = new countUp("myTargetElement", 0, 1635, 0, 7, countOptions);
    customerNumber.start();

});
</script>
jbmnt
  • 11
  • 4

2 Answers2

0

On scroll event check whether target element offset top and document scroll top is same, if same then trigger function

$(document).scroll(function(){
    if($('.myTargetElement').offset().top == $(document).scrollTop()){
        //Trigger function
    }
});
Anjith K P
  • 2,158
  • 27
  • 35
0

The following script fires it as soon as it gets visible (http://jsfiddle.net/f1xbgy86/1/):

$(window).scroll(function() {
                 if(isElementVisible($('#yourElementID'))) {
        $(window).off('scroll');
                     //Call From here

}
});


function isElementVisible(elem)
{
    var visibleTop = $(window).scrollTop();
    var visibleBottom = visibleTop + $(window).height();

    return ((elem.offset().top + elem.height()) <= visibleBottom);
}
Inanda Menezes
  • 1,796
  • 13
  • 17