Loading

Create fixed menu when scrolling page with CSS and jQuery

Do you want to create fixed menu when scrolling page with CSS and jQuery? you already know jQuery right? A short description about jQuery, jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

I decided to create my own way and with only a few lines of CSS and JS code, in this tutorial I only use 2 JS functions to make the fixed menu working.

The aim is to have the navigation fixed when user scrolling the page and back to its original position when scrolling back to top.

Ok, let’s start.
jQuery Library

All we need is only jQuery library; you can download it in jQuery site or use other library from Google CDN, Miscrosoft CDN and jQuery CDN.
HTML

This contains our menu HTML element, this is just a simple HTML UL tag to make our menus but if you already have one then use that instead.

CSS

To make our menu list horizontally we need to add CSS code.

.fixed-nav{ z-index: 9999; position: fixed; left: 0; top: 0; width: 100%;}

We set the z-index very high since we don’t want any other absolute element to be on top of our navigation and add with in percent to center menu while scrolling.
Javascript

This small JS code contains the main functions of our fixed scroll menu.

jQuery(“document”).ready(function($){

var nav = $(‘.container’);

$(window).scroll(function () {
if ($(this).scrollTop() > 126) {
nav.addClass(“fixed-nav”);
} else {
nav.removeClass(“fixed-nav”);
}
});

});

So, if we are on the top less than 126 height in pixel the menu is in the original position and add fixed-nav CSS class when greater than 126px height or add fixed-nav CSS class on scroll, where the top page greater than 126px height.

That’s it, its easy right? Enjoy!

Please follow and like us:
error
Top