1

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

4 Answers 4

3

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/

Sign up to request clarification or add additional context in comments.

2 Comments

in short, this is infact using a debounce
Yes, this is a denouncing mechanism
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(); } } 

Comments

1

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 } 

1 Comment

I wonder why nobody voted this up, this seems the correct and efficient way. thanks !!!
0

There is a nice and clean(er) solution on Stackoverflow here

var timer; $(window).scroll(function(){ if ( timer ) clearTimeout(timer); timer = setTimeout(function(){ // Make your AJAX request here... }, 10000); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.