Sam Skirrow Sam Skirrow - 3 months ago 26
HTML Question

jQuery make div slide in when scrolling down page

I want to make a div slide onto my page from the right when a user scrolls down the page (the div will contain a link that takes them back to the top of the page). Here is the code I'm currently using:

jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > 100) {
jQuery('.totop').animate({ right: '0px' });
} else {
jQuery('.totop').animate({ right: '-300px' });
}
});


And the CSS:

.totop {
position:fixed;
bottom:50%;
right:-300px;
width:300px;
height:100px;
font-size:30px;
color:white;
background:#f18500;
}


The Div is behaving very oddly, when I scroll down the div takes about 5 seconds to appear, then it comes into view but looks like it is making several attempts to slide off again before remaining still, when I slide back to the top it dissapears...but after about 5 seconds again. Would love some help to find out what is wrong with my code please.

Answer

Your animations are getting queued, use .stop():

jQuery(window).scroll(function () {
    if (jQuery(this).scrollTop() > 100) {
        if (jQuery('.totop').hasClass('visible') == false) {
            jQuery('.totop').stop().animate({
                right: '0px'
            }, function () {
                jQuery('.totop').addClass('visible')
            });
        }
    } else {
        if (jQuery('.totop').hasClass('visible') == true) {
            jQuery('.totop').stop().animate({
                right: '-300px'
            }, function () {
                jQuery('.totop').removeClass('visible')
            });
        }
    }
});

DEMO: http://jsfiddle.net/MkJwm/

Comments