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".)