Skip to content

Instantly share code, notes, and snippets.

@madhums
Created March 26, 2011 16:44
Show Gist options
  • Save madhums/888428 to your computer and use it in GitHub Desktop.
Save madhums/888428 to your computer and use it in GitHub Desktop.
Ever seen a sticky header that sticks to the top of window when scrolled?
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
// 'bar' is the id of the box which needs to be fixed
var top = $('#bar').offset().top - parseFloat($('#bar').css('margin-top').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
// if so, add the fixed class
$('#bar').addClass('fixed');
$('body').css('margin-top','0px');
}
else {
// otherwise remove it
$('#bar').removeClass('fixed');
$('body').css('margin-top','0');
}
});
}
/* In the css file you just need to add
.fixed {
position:fixed;
top:0;
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment