How to make div follow scrolling smoothly with jQuery?
Since this question is getting a lot of views and the tutorial linked in the most voted answer appears to be offline, I took the time to clean up this script.
See it live here: JSFiddle
JavaScript:
(function($) {
var element = $('.follow-scroll'),
originalY = element.offset().top;
// Space between element and top of screen (when scrolling)
var topMargin = 20;
// Should probably be set in CSS; but here just for emphasis
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + topMargin
}, 300);
});
})(jQuery);
There's a fantastic jQuery tutorial for this at https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/.
It replicates the Apple.com shopping cart type of sidebar scrolling. The Google query that might have served you well is "fixed floating sidebar".
The solution can be boiled down to this:
var el=$('#follow-scroll');
var elpos=el.offset().top;
$(window).scroll(function () {
var y=$(this).scrollTop();
if(y<elpos){el.stop().animate({'top':0},500);}
else{el.stop().animate({'top':y-elpos},500);}
});
I have changed the assignment of el
because finding a single element by class is not a great habit to get in to; if you only want one element find it by id, if you want to iterate over a collection of elements then find them by class.
please note - my answer here refers to the accepted answer at that time (it still is the accepted answer at the moment, but has since been edited and therefore my answer no longer "boils down" what you see in @Martti Lane's answer on this page; my answer "boils down" his original, accepted, answer; you can take a look at the edit history of @Martti's answer if you're interested in what I "boiled down".)