jQuery Scrolling Question
everyone! I am trying to show a div when user scrolls past another div and hide it again when user reaches the beginning of the latter div. Let's say, we have two divs with IDs #1 and #2. Now, when the user scrolls to the beginning of #1, div#2 is shown. When, again, user comes back to #1, div#2 is hidden. How can I achieve this?
I was using this:
jQuery(window).scroll(function(){
y =开发者_如何学运维 jQuery(window).scrollTop();
if(y>0){
jQuery("#2").slideDown();
}
if(y==0){
jQuery("#2").slideUp();
}
});
which worked perfectly for scrolling on window. But this didn't work:
jQuery(window).scroll(function(){
y = jQuery("#1").scrollTop();
if(y>0){
jQuery("#2").slideDown();
}
if(y==0){
jQuery("#2").slideUp();
}
});
Am I doing it wrong? Help much appreciated.
Think about what scrollTop is to div #1. You say, if y > 0
. Unless div1 itself is scrollable, it will always be zero. What you really want is whether the window is below div1. So for that we use
//top of window is at
jQuery(window).scrollTop();
//top of div1 is at (relative to window)
jQuery('#1').offset().top;
//your code should look like this instead
jQuery(window).scroll(function(){
y = jQuery(window).scrollTop();
if(y>jQuery('#1'.offset().top)){
jQuery("#2").slideDown();
}
else{
jQuery("#2").slideUp();
}
});
精彩评论