Reputation: 5907
I'm using jQuery to fade in a "slide" at the bottom of my page, it's a little tab that's supposed to stick to the right side. I'm currently fading it on a delay, but I'd like to fade it in when the user scrolls down.
This, though, keeps sliding the div across the page, instead of leaving it stuck to the side.
$(function() {
var slide = $("div[data-slide='true']");
$(window).scroll(function() {
var pos = $(document).scrollTop();
console.log(pos);
if ($(document).scrollTop() > 400) {
slide.animate({opacity: 1,right:'+=350'},1350, 'swing').stop();
} else {
slide.clearQueue().animate({opacity: 0,right:'-=350'},500, 'easeOutBounce');
}
});
});
How do I stop the sliding once the initial waypoint is reached? I seem to be able to unbind the scroll event with $(window).unbind('scroll');
but then the slide never animates.
Upvotes: 2
Views: 4570
Reputation: 30135
You are starting a new animation to +350px each time the scroll event is fired, that's why it's moving across the page.
I made a little test to prevent that. I basically add two vars (opening and closing) to prevent the animation from starting multiple times, and changed the animation itself a bit:
Demo:
http://jsfiddle.net/B7pJL/1/
JS:
var slide = $("div[data-slide='true']");
var opening = false;
var closing = false;
$(window).scroll(function() {
var pos = $(window).scrollTop();
console.log(pos);
if (pos > 100) {
if (!opening) {
opening = true; closing = false;
slide.stop().animate({
opacity: 1,
'margin-left': -350
}, 1350, function() {
opening = false;
});
}
} else {
if (!closing) {
closing = true; opening = false;
slide.stop().animate({
opacity: 0,
'margin-left': 0
}, 500, function() {
closing = false;
});
}
}
});
Upvotes: 3