views:

377

answers:

2

Hi,

I'm trying to work out how to get a div (#tips) to appear when the user scrolls into the 2nd quarter of its containing div's height (#wrap), and then have it disappear when the user scrolls into the last quarter. So it would be like this:

1st quarter - #tips is hidden
2nd quarter - #tips is visible
3rd quarter - #tips is visible
4th quarter - #tips is hidden

I'm almost completely new to jQuery but what I've got so far is this:

function addKeyboardNavigation(){
 // get the height of #wrap
 var $wrapHeight = $('#wrap').outerHeight()
 // get 1/4 of wrapHeight
 var $quarterwrapHeight = ($wrapHeight)/4
 // get 3/4 of wrapHeight
 var $threequarterswrapHeight = 3*($wrapHeight)
 // check if we're over a quarter down the page
 if( $(window).scrollTop() > $quarterwrapHeight ){
  // if we are show keyboardTips
  $("#tips").fadeIn("slow");
 }
}

This is where I get confused. How can I check if the scroll position is > $quarterwrapHeight but < $threequarterswrapHeight?

To make it run I've been using:

// Run addKeyboardNavigation on scroll
$(window).scroll(function(){
 addKeyboardNavigation();
});

Any help or suggestions would be greatly appreciated!

Thanks.

+1  A: 

How about:

if(($(window).scrollTop() > $quarterwrapHeight) && ($(window).scrollTop() < $threequarterswrapHeight)){
   $("#tips").fadeIn("slow");
} else {
   $("#tips").fadeOut("slow");
}
zaf
Thanks for the quick reply, maybe I need to be clearer though. I'd like the #tips div to hide itself when the user's scroll position is in the 1st and 4th quarters of the height of the #wrap div.
Rik
An else after the if statement with a fadeOut? Updated my answer.
zaf
Aye I tried that too, it didn't work though. The answer below works but I'm not sure that it's much different. Odd. Thanks nevertheless.
Rik
+1  A: 

Hi I posted a demo here... the only problem is if your #wrap div isn't tall enough, the top of the window will never get to the 3/4 height, so the tooltip won't fade out. Here is the code:

$(document).ready(function(){
 $(window).scroll(function(){
  // get the height of #wrap
  var h = $('#wrap').height();
  var y = $(window).scrollTop();
  if( y > (h*.25) && y < (h*.75) ){
   // if we are show keyboardTips
   $("#tips").fadeIn("slow");
  } else {
   $('#tips').fadeOut('slow');
  }
 });
})

I used height() but you can use outerHeight()... I forgot to change it in the demo because originally I was using the body instead of the #wrap.

Another problem would be if the #wrap isn't located at the top of the page. If it's further down, then you'll have to subtract it's position on the page from the scrollTop:

var y = $(window).scrollTop() - $('#wrap').position().top;
fudgey
Fantastic, that works great. #wrap is handily as big as body (using it to get a stuck-to-the-bottom footer) so it's not an issue. Thanks!
Rik