0

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?

2
  • Put it not more than 300px from the top of the page. You won't even need jQuery :-)
    – edeverett
    Commented Aug 30, 2009 at 21:28
  • I want it fixed to the browser, so when you scroll down, it will look cool :D Commented Aug 30, 2009 at 21:42

4 Answers 4

2
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

0
1

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.

1
  • Note that scrollTop does NOT work across browsers. You want window.scrollY for this test. Commented Mar 4, 2010 at 0:47
1

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

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.