Quick Code: jQuery Sticky Navigation When User Scrolls

Written by
Published
Typical Read
1 minutes

Sticky navigation is being used more and more on sites and there's a good reason why. It improves the UX by making the menu available no matter where the user is on the page. Learn how to create a simple, light-weight jQuery sticky navigation below. Best of all, it's easy to implement on existing site's without having to change any existing HTML code!

Sticky navigation is being used more and more on sites and there’s a good reason why. It improves the UX by making the menu available no matter where the user is on the page. Learn how to create a simple, light-weight jQuery sticky navigation below. Best of all, it’s easy to implement on existing site’s without having to change any existing HTML code!

jQuery Sticky Navigation Effect

Without further adieu, let’s jump into the code.

The JavaScript

[js]jQuery(function(){
var menuOffset = jQuery(‘#site-navigation’)[0].offsetTop;
jQuery(document).bind(‘ready scroll’,function() {
var docScroll = jQuery(document).scrollTop();
if(docScroll >= menuOffset) {
jQuery(‘#site-navigation’).addClass(‘fixed’).css(‘width’,jQuery(‘#masthead’).width());
} else {
jQuery(‘#site-navigation’).removeClass(‘fixed’).removeAttr("width");
}
});
});[/js]

Fairly basic jQuery code. It will add a class to the navigation when a user scrolls beyond it. Only thing you’ll need to change here is the navigation selector, #site-navigation. Also, you may want to remove .css('width',jQuery('#masthead').width()). That part of the code is more specific to this site.

The CSS

[js]#site-navigation.fixed{
position:fixed;
z-index: 9999;
top:0;
}[/js]

Simple stuff! If you’ve got any questions or need help customizing it to meet your needs feel free to shoot me a line below.

1 comment on “Quick Code: jQuery Sticky Navigation When User Scrolls”.

Kirill

# Aug 28, 2014

Really nice post and working code, i used it on one project with Bootstrap 3 for header element.
Thank you, Ben

Join the conversation.

Your email address will not be published. Required fields are marked *

All comments posted on 'Quick Code: jQuery Sticky Navigation When User Scrolls' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.