Skip to content

Instantly share code, notes, and snippets.

@raym
Last active August 29, 2015 14:07
Show Gist options
  • Save raym/4b25ac47203d4139884f to your computer and use it in GitHub Desktop.
Save raym/4b25ac47203d4139884f to your computer and use it in GitHub Desktop.
javascript for having a sidebar element follow you as you scroll -- behavior modeled after facebook sidebar
var wrapperId = 'sidebarWrapperIdOnPage';
var
$w = $(window),
$wrap = $('#'+wrapperId),
followerInitialOffset = $wrap.offset().top,
marginTop = 0,
$wrap, windowTop, windowBottom, followerHeight,
followerTop, followerBottom, followerBottomPosition
;
$w.scroll(function() {
windowHeight = $w.height();
windowTop = $w.scrollTop();
windowBottom = windowTop + windowHeight;
followerHeight = $wrap.height();
followerTop = $wrap.offset().top;
followerBottom = followerTop + followerHeight;
if (windowHeight > followerHeight || windowTop < followerTop) {
marginTop = Math.max(windowTop - followerInitialOffset, 0);
} else if (windowBottom > followerBottom) {
marginTop = windowBottom - followerHeight - followerInitialOffset;
}
$wrap.css({'margin-top': marginTop});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment