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?
4 Answers
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
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.
-
Note that scrollTop does NOT work across browsers. You want
window.scrollY
for this test. Commented Mar 4, 2010 at 0:47
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.