I know this looks like a pretty big piece of code, however this function just works by specifying three simple options; your floating "top", your "target" (floater) and the "reference" element to set the borders, it also automatically takes care of the upper and lower positions, css is not involved.
function scrollFloater(marginTop, reference, target, fixWhidth = false){ var processScroll = function(){ var from = reference.offset().top - marginTop; var to = reference.offset().top + reference.outerHeight() + marginTop - target.outerHeight(); var scrollTop = $(this).scrollTop(); var bottom = to - reference.offset().top + marginTop; if( fixWhidth ) target.css('width', target.width()); if( scrollTop > from && scrollTop < to ) target.css('position', 'fixed').css('top',marginTop); else if( scrollTop >= to ) target.css('position', 'absolute').css('top', bottom); else target.css('position', '').css('top',marginTop); } $(window).scroll(function(){ processScroll(); }); processScroll(); }
And here is how you use it:
$(function() { scrollFloater(41, $('.box.auth.register'), $('.plans-floater'), true); });
I hope this helps someone.
human source share