Animate position of div on scroll position

11,612

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);
     }
});
Share:
11,612
John the Painter
Author by

John the Painter

Updated on June 04, 2022

Comments

  • John the Painter
    John the Painter almost 2 years

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

    UPDATE FOR REWARD

    This is the dev site I am working on: http://goo.gl/KcFdE6 and as you can see, if you scroll to the bottom and stop, it slides up fairly well, BUT, if you keep scrolling... it's interacting with the animation and you can a really jumpy/slow transition. Any ideas?