0

I'm trying to fire an event when scrolling down to a certain point/value and execute again when scroll back up and down again.

I tried:

$(window).scroll(function(){
    var sTop = $(this).scrollTop();

    if(sTop == 300){
        //execute event - failed
    }

});

The above does not fire anything with the both mousewheel and dragging the scrollbar. but when I changed the condition to greater than or equal to, the event is being executed but multiple times when scrolling further down.

if(sTop >= 300){
    //execute event - success
}

I also tried changing the condition value and some times the event is being fired.

if(sTop == 333 /* or 431, 658, etc. */){
    //execute event - sometimes success
}

Here is my test fiddle.

Could it be that scroll() function sometimes skips a value if you scroll fast?

Can someone explain the issue and help me with a workaround on how to trigger an event when the $(window).scrollTop() == 'value'. Thanks

Mark S
  • 3,789
  • 3
  • 19
  • 33
  • It is working. `==300` triggers the alert as expected. – karthikr Nov 18 '13 at 02:51
  • 1
    Do you want it to execute again if the user scrolls back up and down again? It might help if you explain what kind of function you want to execute and why. – godfrzero Nov 18 '13 at 03:03

1 Answers1

0

You're facing this issue because there are no guarantees that scrolling will be done in increments of 1. For example, some scroll wheels increment in values of 30. This means that you'd get a scroll event on 30, 60, 90, etc.

The best way to test if scrolling has reached your limit is to see if it has gone past the point you're wanting, then resetting the scroll to the precise point you're wanting. So you'd do:

if(sTop >= 300){
    $(window).scrollTop(300);
}

Here's an updated link to your JSFiddle with a working example: http://jsfiddle.net/bC3Cu/4/

If you take a look at unit of increment in scrollable areas / divs in javascript? it describes how to set it to where you can override the scroll increment. Using that method, you should be able to predict how many units the user has scrolled without preventing them from scrolling further down the page.

Community
  • 1
  • 1
aust
  • 914
  • 4
  • 12
  • If you use the code on line 3 of $('div').append(',' + sTop); You'll see the increments are larger than 1. You'll need to change the basic logic as there may never be a sTop == 300 – matt.j.crawford Nov 18 '13 at 02:56
  • Wouldn't this also prevent the page from scrolling at all past 300px? – godfrzero Nov 18 '13 at 03:01
  • I see. But I still want to be able to scroll further below. Is there a way to get the scrolling increment value? – Mark S Nov 18 '13 at 03:01
  • @godfrzero This will definitely prevent it from scrolling past 300px. – aust Nov 18 '13 at 03:02
  • @Mark S See http://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers – aust Nov 18 '13 at 03:04