I came across a post from Karthik Vadlapatla on Forrst who was looking for a way to make a navigation bar stick to the top when the document is scrolled down past a certain amount, as seen on the Zendesk website. The effect basically involves attaching a scroll event to the document or window that will change the css on the menu when the document scroll past the top offset position of the menu bar.
The general reason for using this effect to improve accessibility in that the user does not have to scroll all the way back to the top of the page to access the navigation bar. The code below illustrates how this is done:
$(function(){
var menuOffset = $('#menu')[0].offsetTop; // replace #menu with the id or class of the target navigation
$(document).bind('ready scroll',function(){
var docScroll = $(document).scrollTop();
if(docScroll >= menuOffset){
$('#menu').addClass('fixed');
} else {
$('#menu').removeClass('fixed');
}
});
});
The code above will add a class to the target navigation, allowing you to set some custom css that is attached to the class:
#menu.fixed{
background: #777;
position:fixed;
left:0;
top:0;
width:100%;
}
You can view the full demo on jsFiddle.
July 12th, 2012 at 9:36 pm
Great and simple code, I just used it and it works great! Thanks a lot