jQuery scroll calls a function multiple times

2019-07-22 13:56发布

问题:

I have a jquery scroll function as below :

$(window).scroll(function() {
if (($(window).scrollTop() + $(window).height()) >= ($('body').height() * 0.7)) {
        alert('call me');
     }
});

And the HTML:

<div style="height:450px;">BOX</div>

When I scroll, instead of just one call me I am getting multiple times call me. Why so and whats wrong ? JSFiddle Example Here

回答1:

It's a feature not a bug, is normal to receive it each time the scroll event happens, the scroll event is launched every time the position of an element within the scrollbars is changed.

You can add a flag, a class or a timeout to avoid it if don't want it.

For example with a timeout you may do it like this:

JS:

var timeout;

$(window).scroll(function() {
    if(typeof timeout == "number") {
      window.clearTimeout(timeout);
      delete timeout;
   }
   timeout = window.setTimeout( check, 100);
});

function check(){
if (($(window).scrollTop() + $(window).height()) >= ($('body').height() * 0.7)) {
        alert('Call me!')
     }
}

The fiddle is here : http://jsfiddle.net/f3C6Y/2/



回答2:

There may be other ways to do this, but you could set a CSS class once its called then check if that class exists before you try to call it again... Something like this:

function callfunction() 
{
    if (($(window).scrollTop() + $(window).height()) >= ($('body').height() * 0.7)) {
    $('body').addClass('called');
    alert('call me');
    }
}

$(document).scroll(function () { 
    if(!$('body').hasClass('called')) 
    {
        callfunction();
    }
}


回答3:

a timer is bad, it creates a lot of programming overhead... adding classes makes the code slow as well. You're binding a function and doing a check for a parameter every time the user scrolls. That's a HUGE waste of resources!

if you want to call a function ONCE on the user scrolling unbind the function at the first call:

function callfunction(){
   $(window).unbind("scroll");
   //*... do the rest of your programming here
}