1

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);
    }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Barney
  • 1,820
  • 5
  • 29
  • 50
  • 1
    @RoryMcCrossan: I have not downvoted but I would assume that a downvote wihtout a comment implies that the person who downvoted it found the question met what is stated in the tooltip: either did not show research effort, was unclear, or not useful. Hence the answer to your question is propably because one of the three applied to that person. Back on topic, +1 on the question from me. I think it is a useful question. There is always lots to learn about animations and timeouts. For smooth transitions beyond jQuery capabilities CSS transformations might be a way to go if it is a choice for OP. – Nope Nov 28 '12 at 13:24

1 Answers1

3

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)
});

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Sometimes I'm not sure if the success of stack overflow is due to its well thought out design or the value of some of its helpful and knowledgable user base. Thankyou! :) – Barney Nov 28 '12 at 13:23
  • 1
    +1 for a good/useful answer. @Barney: In addition jQuery animation has it's limits regarding smoothness. In your case it will do fine but if you ever get stuck and frustrated with jQuery animations, try looking into CSS3 transformations. Very smooth and most browsers support a huge range of it already. IE being the exception off course in most cases. Regarding your question in your comment: the answer would be both in my opinion. One would not work without the other. It is not perfect by no means but it is well-ish balanced. – Nope Nov 28 '12 at 13:30