Reputation: 21
I want scrollTop to trigger only once, so that the red box doesn't appear again after it has been closed with the button.
I know there is .one(), but I have no idea how to apply it to my code. Below is my code and jsfiddle.
<div id="box-pop">This is a red box.
<button class="box-close">Close</button>
</div>
$(document).scroll(function () {
if ($(this).scrollTop() > 100) {
$('#box-pop').fadeIn(500);
}
});
$(document).ready(function () {
$(".box-close").click(function () {
$("#box-pop").fadeOut(200)
});
});
Upvotes: 2
Views: 1144
Reputation: 1547
For a better performance in your page, what about this?
$("#box-pop").fadeOut(200,function(){
$(this).remove();
});
Demo: http://jsfiddle.net/3LG6t/5/
And take a look at this topics:
Upvotes: 3
Reputation: 842
if you are using scroll for other functionallity, you need to create separate function, otherwise see @Gavin42 example
fadeInBox = function () {
if ($(window).scrollTop() > 100) {
$('#box-pop').fadeIn(500);
}
}
$(document).on('scroll', fadeInBox);
$(document).ready(function () {
$(".box-close").click(function () {
$(document).off('scroll', fadeInBox);
$("#box-pop").fadeOut(200);
});
});
Upvotes: 0
Reputation: 33834
One is used the same way bind or on is. Scroll itself really isn't an actual function but a shortcut to on that performs the following:
.on('scroll', function () {
}
However you need to get something to work once after a condition, so you would use off after using on.
<div id="box-pop">This is a red box.
<button class="box-close">Close</button>
</div>
$(document).on('scroll', function fadeBoxIn() {
if ($(this).scrollTop() > 100) {
$('#box-pop').fadeIn(500);
$(document).off('scroll', fadeBoxIn);
}
});
$(document).ready(function () {
$(".box-close").click(function () {
$("#box-pop").fadeOut(200)
});
});
See the fiddle.
Upvotes: 2
Reputation: 490
Try $( "document").unbind( "scroll" );
:
$(document).scroll(function () {
if ($(this).scrollTop() > 100) {
$('#box-pop').fadeIn(500);
}
});
$(document).ready(function () {
$(".box-close").click(function () {
$("#box-pop").fadeOut(200)
$(document).unbind("scroll");
});
});
or conditionally rebind the scroll function within the $(".box-close").click()
.
Upvotes: 0