Top Fixed Menu Bar on Scroll with CSS & jQuery – Less Code

Here I am writing minimum code to make Top Fixed Menu Bar on Scroll with CSS & jQuery. The purpose of this article is to  have the navigation menu fixed at top when visitors scroll down the page and place menu back to it’s original position when scrolling back to upside.

There are plenty of tutorials on internet but they contain lots of script and CSS to obtain the fixing as well as there is a little buggy behaviour: The page jumps up a little when navigation becomes on the top of everything while using those tutorials.

Top Fixed Menu Bar on Scroll with CSS & jQuery

In this article we are nicely creating Top Fixed Menu Bar on Scroll with CSS & jQuery with less code required (minimum JS and CSS) and no page jumping, only smooth scrolling!

VIEW DEMO

jQuery Library

We need jQuery library in our page so download from jQuery site and add it or you can use other jQuery libraries from CDN as well.

HTML

The HTML contains our menus made using unordered list. If you already have that then use them and don’t forget to replace the classes in JS code.

CSS

The two required CSS rules to apply when menu reaches at top are:

The  first rule has z-index very high as we don’t want any other absolute element to be on top of our navigation. The second rule set the margin-top of the body (offset) to the height of the menu when you fix the menu, this stops the rest of the content “jumping” by the height of the menu when it becomes fixed.

Rest of the CSS rules are used for formatting and horizontal appearance of the menu:

Javascript

This small JS code below contains function to obtain top fixed menu bar on scroll:

This code adds/removes required classes to corresponding elements depending upon current scroll position and top offset coordinate of the nav elements wrapper (nav-container) using jQuery toggleClass. This behavior is similar to:

That’s all and it’s easy to implement. VIEW DEMO  or the complete code is here!

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.