Skip to content

Instantly share code, notes, and snippets.

@ezy
Created August 28, 2013 05:04
Show Gist options
  • Save ezy/6362311 to your computer and use it in GitHub Desktop.
Save ezy/6362311 to your computer and use it in GitHub Desktop.
JS for conditional fixing of a CSS element in a page
JavaScript
$(document).scroll(function(){
var elem = $('.subnav');
if (!elem.attr('data-top')) {
if (elem.hasClass('navbar-fixed-top'))
return;
var offset = elem.offset()
elem.attr('data-top', offset.top);
}
if (elem.attr('data-top') <= $(this).scrollTop() )
elem.addClass('navbar-fixed-top');
else
elem.removeClass('navbar-fixed-top');
});
CSS
.subnav {
background:#FFF;
}
.navbar-fixed-top {
position:fixed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment