Skip to content

Instantly share code, notes, and snippets.

@coffeencoke
Created June 7, 2012 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coffeencoke/2891030 to your computer and use it in GitHub Desktop.
Save coffeencoke/2891030 to your computer and use it in GitHub Desktop.
$(function(){
$('.subnav').fixElementOnScroll(45, 'subnav-fixed');
$('.sidebar-nav').fixElementOnScroll(113, 'fixed');
});
.sidebar-nav.fixed{
position: fixed;
top: 99px;
left: 20px;
width: 19.5%;
}
.subnav-fixed{
position: fixed;
top: 40px;
height: 40px;
left: 0;
right: 0;
}
/*
* This will add a class to all matching elements when they reach a specific point when scrolling
* and will remove the class after going back to the point. Similar to how twitter bootstrap's secondary
* nab works on this page (http://twitter.github.com/bootstrap/scaffolding.html) as you scroll.
* Notice how it snaps to the top and remains fixed.
*/
(function( $ ){
$.fn.fixElementOnScroll = function(heightOffset, classForFixing) {
if(this.length > 0){
var $win = $(window);
var topOfFixPoint = this.length && this.offset().top - heightOffset;
var $this = this;
$win.on('scroll', function(){
var isFixed = $this.hasClass(classForFixing);
var i, scrollTop = $win.scrollTop();
var shouldFixElement = scrollTop >= topOfFixPoint && !isFixed;
var shouldUnfixElement = scrollTop <= topOfFixPoint && isFixed;
if (shouldFixElement || shouldUnfixElement) {
$this.toggleClass(classForFixing);
}
});
}
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment