views:

275

answers:

4

How do I detect if a user scrolls downwards with jQuery? I want a fixed div to show only when the browser is within 300px of the top. When the user scrolls down past the 300px mark, it should disappear. When the user scrolls back to the top, it should hide. How do I do this?

+1  A: 
var docElem = $(document.documentElement)
docElem.scroll(function(e) {
    if(docElem.scrollTop() < 300) {
        whatever.show();
    } else {
        whatever.hide();
    }
});

You may have to use a different element (as docElem) in different browsers, but this should work in Firefox. (I haven't tested it)

EDIT: More jQuery

SLaks
I used some of your code, thanks!
Brandon Wang
Then why didn't you mark it accepted?
SLaks
+1  A: 

Attach a scroll listener to the window: http://docs.jquery.com/Events/scroll

Then check the scrollTop of window: http://docs.jquery.com/CSS

When scrollTop is less than 300, show() the div, otherwise hide() it.

Xanthir
Note that scrollTop does NOT work across browsers. You want `window.scrollY` for this test.
Karl Guertin
+1  A: 

scrollTop and scrollY look like they will get you started in IE and Firefox. Not sure about other browsers.

edeverett
A: 

Just check the window scrollTop position on the scroll event, and compare it with the element offsetTop position:

$(window).scroll(function(e){ 
  $el = $('.myElement'); 
  if ($(this).scrollTop() > $el.offset().top){ 
    $el.hide(); 
  } else { 
    $el.show();
});

Run this example here.

CMS