views:

64

answers:

3

I am using jQuery to hide a div on my page:

$(document).ready(function(){   
$('#message').hide();

When a certain part of the page scrolls into view the div shows using

$(window).scroll(function() {

            var top = 0;
            top = $(window).scrollTop();


            if((top >= 1000) && (top < 2000)){

                $('#message').fadeIn('slow');
            }    
            }

I want to add a close button to this as follows

$('a#message-hide').click(function() {
$('#message').hide('fast');
return false;

All good so far but the part I cannot figure out is how to then STOP the div re-appearing when the user scrolls back to the trigger position on the page...?

+2  A: 

You can rearrange your code a bit so it's unbindable (in a way that doesn't do collateral damage), like this:

 function checkShowDiv() {
   var top = $(window).scrollTop();
   if(top >= 1000 && top < 2000) {
     $('#message:hidden').fadeIn('slow'); //prevent re-fades with :hidden
   }
 }
 $(window).scroll(checkShowDiv);

Then in your close function:

$('a#message-hide').click(function() {
  $(window).unbind('scroll', checkShowDiv);
  $('#message').hide('fast');
  return false;
});

What this does is both close the <div>, and .unbind() the check that happens on scroll that might show it again.

Nick Craver
Thanks Nick, this works great apart from if the close button is inside the #message div... could this be achieved with .parent ...?
Jonny Wood
@Jonny - Since you're using IDs either way it should work, but if the parent div had a classe say `.closeMe`, you could do `$(this).closest('.closeMe').hide('fast');`...but your IDs should be unique anyway, is that not the case?
Nick Craver
Sorry, I spoke too soon. it works perfectly!I did think it was odd that it wouldn't work in the div, don't know what I did wrong but it's all sorted now. Thanks for your help!
Jonny Wood
A: 

@Nick Craver answer will work only if you want to stop the div being re appeared even after user closes the div. But your code will make the div fade in continuously when you scroll bet ween 1000 and 2000. to stop the behavior, you can have a flag which indicates if the div is being displayed and check the flag before displaying the div.

Elangovan
Actually this would be better solved like this: `$('#message:hidden').fadeIn('slow');` I'll update the answer to handle it.
Nick Craver
+1  A: 
$('a#message-hide').click(function(e) {
   e.preventDefault(); // Better than returning false
   $('#message').remove(); // Remove the message forever
});

With this you will simply remove the #message element from your page and when the user scroll to "trigger position" it'll not be displayed again.

TiuTalk
It's worth noting this doesn't do what the OP has, his current code fades out, you would need `$("#message").fadeOut('fast', function() { $(this).remove(); });`, but if the user scrolls during fadeout, there are still issues there.
Nick Craver