$(document).ready(function(e) { t = $('.fixed').offset().top; mh = 3000; fh = 300; $(window).scroll(function(e){ s = $(document).scrolltop(); if(s > t - 10){ $('.fixed').css('position','fixed'); if(s + fh > mh){ $('.fixed').css('top',mh-s-fh+'px'); } }else{ $('.fixed').css('position',''); } }) });