Last active
August 29, 2015 14:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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