javascriptjqueryhtmlcssanimation

Animate position of div on scroll position


What's the best way to animate the position of a div on scroll position? Essentially, when you reach a certain point on the page... a fixed element will animate up.

I have included below what I currently have... but it's a little slow and seems to slide up... slowly... half way... then complete. Any thoughts?

var shareHeight = $('.related-share-container').height();
$('.related-share-container').css('bottom',-shareHeight);
$(window).scroll(function() {   
     if ($(window).scrollTop() + $(window).height() > $(document).height() - 150) {
        $('.related-share-container').stop().animate({ bottom: 0 }, 500);
     } else {
         $('.related-share-container').stop().animate({ bottom: -shareHeight }, 500);
     }
});

Solution

  • It is happening cause for each scroll movement previous animation get stopped and new begins, which is slower than previous one cause it has less distance to animate. Thus you need some flag in your code to prevent same animation triggering again and again.

    Modified JS:

    Here I am using done class as a flag.

    var shareHeight = $('.related-share-container').height();
    $('.related-share-container').css('bottom',-shareHeight);
    $(window).scroll(function() {   
         if ($(window).scrollTop() + $(window).height() > $(document).height() - 150) {
             if(!$('.related-share-container').hasClass('done'))
                 $('.related-share-container').addClass('done').stop().animate({ bottom: 0 }, 500);
         } else {
             if($('.related-share-container').hasClass('done'))
                 $('.related-share-container').removeClass('done').stop().animate({ bottom: -shareHeight }, 500);
         }
    });