Skip to content

Instantly share code, notes, and snippets.

@bitops
Forked from raym/followScroll.js
Created October 2, 2014 05:14
Show Gist options
  • Save bitops/be89b11783fb9dd9334d to your computer and use it in GitHub Desktop.
Save bitops/be89b11783fb9dd9334d to your computer and use it in GitHub Desktop.
var wrapperId = 'wrapperIdOnPage';
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