zack
zack

Reputation: 484

jQuery animate on window scroll

I want to slid a div on window scroll to bottom. When document reach 800 (bottom) Div should scroll right 0 and less then 800 it should slid and hide.

Problem is when scrolling to bottom div is sliding and showing but again when scrolling to top it doesn't slid and hide.

This is my code

$(document).scroll(function () { // remove "$"
    var s = $("#slidebox");
    var y = $(this).scrollTop();        
    if (y > 800) {
        s.animate({"right":"-450px"}, "slow");
    } else if (y < 800) {

        s.animate({"right":"0px"}, "slow");
    }
});

Basically i want is to hide and show (with a slid effect) div on document scroll to bottom.

Check scrolling below jsfiddle.

jsfiddle

Upvotes: 0

Views: 1105

Answers (2)

Brian
Brian

Reputation: 7654

On one hand, user390....'s response is correct in that the height is calculated incorrectly.

On the other hand, the way animations work is that they queue up one after another, so sometimes the div doesn't slide in/away until everything else before it is done. Using .stop() fixes the issue.

var s = $("#slidebox");

$(document).scroll(function () { // remove "$"
    var y = $(this).scrollTop() + $(window).height();        
    console.log(y);
    if (y > 800) {
        s.stop().animate({"right":"-450px"}, "slow");
    } else {
        s.stop().animate({"right":"0px"}, "slow");
    }
});

Upvotes: 3

Nathan Peixoto
Nathan Peixoto

Reputation: 328

Your problem is that the value you are using for your "Did I reach the bottom" if statement is wrong.

Here is the calculated value you should be using:

$(document).scroll(function () { // remove "$"
    var s = $("#slidebox");
    var y = $(this).scrollTop();
    var bottom = jQuery(document).height() - jQuery(window).height();
    if (y >= bottom) {
        s.animate({"right":"-450px"}, "slow");
    } else {
        s.animate({"right":"0px"}, "slow");
    }
});

Plus, I'd also recommand you to use a .stop(true, true) on your animated element before triggering the "animate" function if you don't want people to mess around with it.

Upvotes: 1

Related Questions