Make an element sticky once it has scrolled out of view in a scrollable <div>
Last active
August 29, 2015 14:03
-
-
Save jasesmith/0fd8d5196481c77d512e to your computer and use it in GitHub Desktop.
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
.bar { | |
position: relative; | |
} | |
.sticky-bar .bar { | |
position: fixed; | |
left: 0; // or whatever makes it fit | |
right: 0; // or whatever makes it fit | |
} |
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 stickyBar = function(bar, pane) { | |
var $body = $('body'), | |
$bar = $(bar), | |
$pane = $(pane), | |
barHeight = $bar.outerHeight(true), | |
$barParent = $bar.parent(), | |
offset = $bar.offset().top - $pane.offset().top + barHeight; | |
$pane.on('scroll', function() { | |
var distance = $pane.scrollTop(); | |
$body.toggleClass('sticky-bar', (distance > offset)); | |
if($body.hasClass('sticky-bar')) { | |
$bar.css({top: Math.floor($pane.offset().top)}); | |
$barParent.css({paddingTop: barHeight}); | |
} else { | |
$bar.css({top: 0}); | |
$barParent.css({paddingTop: 0}); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment