Reputation: 1848
I'm sliding a DIV into the viewport horizontally after a user has scrolled down (x) pixels. It then scrolls out again if they scroll back up. However the way it slides seems to be very very jerky (it pauses at moments too).
<div id="doom_o"></div>
div#doom_o {
position: fixed;
left: -300px;
z-index: -1;
height: 400px;
width: 309px;
background-image: url("../images/doom_o.png");
background-repeat: no-repeat;
}
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
setTimeout(function() {
$('#doom_o').stop().animate({left: "20%"});
}, 250);
}
else {
setTimeout(function() {
$('#doom_o').stop().animate({left: "-300px"});
}, 250);
}
});
Upvotes: 1
Views: 511
Reputation: 337560
You need to remove the setTimeout
calls from the if
condition and then put the whole block into it's own setTimeout
. This will mean that the code is only run once as the scrolling finishes, rather than every time the scroll event fires which is what causes the stuttering.
var timer;
$(window).scroll(function() {
clearTimeout(timer);
var timer = setTimeout(function() {
if ($(this).scrollTop() > 100) {
$('#doom_o').stop().animate({ left: "20%" });
}
else {
$('#doom_o').stop().animate({ left: "-300px" });
}
}, 150)
});
Upvotes: 3