Reputation: 369
Im trying to make button which appears if scrollTop > 200 and hide when scrollTop < 200. However i would like the button to fadein and there comes the problem.
Heres my javascript:
$(window).scroll(function(){
if($(this).scrollTop() > 200) {
$(".button").removeClass("opacity");
}
else {
$(".button").addClass("opacity");
};
and Css:
.opacity { opacity:0; }
With code like this the show/hide function works fine but cant make it to fadein. I also tried changing my jscript to this:
$(window).scroll(function(){
if($(this).scrollTop() > 200) {
$(".button").animate({"opacity":"1"}, 1500);
else {
$(".button").animate({"opacity":"0"}, 1500);
};
But with this it doesnt work at all.
Last thing I tried was fadeIn and fadeOut property which worked, but then the other buttons under this one changed their position after it showed/hidden (the buttons are position:fixed; scrolling with page), making the effect not really nice..
Any ideas how i could make it to fadein and fadeout? Thank you
Upvotes: 2
Views: 6708
Reputation: 455
VisioN's answer seems to work. The only thing I'd add is a boolean to keep track of when the button is animating.
var animating = false;
That way your if statement would be something like
if ($(this).scrollTop() > 200 && !animating) { ...
Purpose being, the way it is now the animation continues to reset as the user keeps scrolling, each time with an interval set to 1.5 seconds. So the button won't fade in completely until you stop scrolling, which might not be what you want. To fix you'd set the 'animating' boolean to true when you set the fade-in, then set it back to false in the callback function.
Upvotes: 0
Reputation: 145378
Your code looks good, however I would better add stop
methods and make duration less. This should work fine:
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$(".button").stop().animate({
opacity: 1
}, 500);
} else {
$(".button").stop().animate({
opacity: 0
}, 500);
}
});
DEMO: http://jsfiddle.net/qXunw/
Upvotes: 5