jQuery show div click to hide then do not show again
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;
开发者_如何学Python 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...?
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.
$('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.
@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.
精彩评论