A navigation menu that stays on top with jQuery

A navigation menu that stays on top with jQuery

This is an easy way to make a navigation menu that sticks to top of the window while scrolling down the page. We want the menu to stick to the top only after we've scrolled down further than its original position. A few lines of jQuery will to the trick. Here is the markup:

HTML

<div id="demo_top_wrapper">

    <!-- a header with a logo just to have some content before the menu -->
    <div id="demo_top">
        <div class="demo_container">
            <div id="my_logo">Our logo</div>
        </div>
    </div>

    <!-- this will be our navigation menu -->
    <div id="sticky_navigation_wrapper">
        <div id="sticky_navigation">
            <div class="demo_container">
                <ul>
                    <li><a href="#" class="selected">HOME</a></li>
                    <li><a href="#">ABOUT US</a></li>
                    <li><a href="#">SERVICES</a></li>
                    <li><a href="#">CLIENTS</a></li>
                    <li><a href="#">PARTNERS</a></li>
                    <li><a href="#">CONTACT</a></li>
                </ul>
            </div>
        </div>
    </div>

</div><!-- #demo_top_wrapper -->

<!-- some other content should go here, in order to have a scrollbar -->

CSS

.demo_container { width:980px; margin:0 auto; }
#demo_top_wrapper { margin:0 0 20px 0; }
#demo_top { height:100px; padding:20px 0 0 0; }
#my_logo { font:70px Georgia, serif; }

/* our menu styles */
#sticky_navigation_wrapper { width:100%; height:50px; }
#sticky_navigation { width:100%; height:50px; background:url(trans-black-60.png); -moz-box-shadow: 0 0 5px #999; -webkit-box-shadow: 0 0 5px #999; box-shadow: 0 0 5px #999; }
#sticky_navigation ul { list-style:none; margin:0; padding:5px; }
#sticky_navigation ul li { margin:0; padding:0; display:inline; }
#sticky_navigation ul li a { display:block; float:left; margin:0 0 0 5px; padding:0 20px; height:40px; line-height:40px; font-size:14px; font-family:Arial, serif; font-weight:bold; color:#ddd; background:#333; -moz-border-radius:3px; -webkit-border-radius:3px; border-radius:3px; }
#sticky_navigation ul li a:hover, #sticky_navigation ul li a.selected { color:#fff; background:#111; }

jQuery

$(function() {

    // grab the initial top offset of the navigation 
    var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;
    
    // our function that decides weather the navigation bar should have "fixed" css position or not.
    var sticky_navigation = function(){
        var scroll_top = $(window).scrollTop(); // our current vertical position from the top
        
        // if we've scrolled more than the navigation, change its position to fixed to stick to top,
        // otherwise change it back to relative
        if (scroll_top > sticky_navigation_offset_top) { 
            $('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 });
        } else {
            $('#sticky_navigation').css({ 'position': 'relative' }); 
        }   
    };
    
    // run our function on load
    sticky_navigation();
    
    // and run it again every time you scroll
    $(window).scroll(function() {
         sticky_navigation();
    });

});

Comments

Alberto  •  March 2, 2012 07:28

Thanks, Great tutorial.

I just have one question:

Playing with the demo i increased the height of the id demo-top, to 1000px because in my site i have a navigation bar at that position. but as soon as i scrolled the demo the nav became fixed and appear on top.

i would wish to know how to code it so, the navigation become fixed once i have scrolled till 1000px in my site and from there follow my scrolling

it is possible with this code?

thanks in advance

Jai  •  March 22, 2012 13:18

Is there anybody know from where I can get this navigation bar? http://www.iniyant.com/

Simo  •  March 30, 2012 05:38

I'm trying to get this working with version 1.7.1 of jquery but with no luck (the latest version as of my writing is 1.7.2).

I can get this to work offline if i use jquery 1.6.4 as in the examples, but i'm coding this into a wordpress site and apparently changing the jquery version isn't the best idea for security's sake.

Any chance you can update the code or show me what i need to change so i can get this working with jquery 1.7.1 or above?

Thanks very much!
~Simo

brion  •  April 4, 2012 22:26

wow brilliant.
ive been looking all day for a simple way to get the nav visible at all times and this was the simplest.
thanks so much!
bri

patrioticcow  •  April 5, 2012 22:57

nice. some people ,mighty want to add 'z-index': 100000 so the menu will stay on top of any image sliders or whatever

Simo  •  April 10, 2012 13:27

I got around the jquery version problem in Wordpress by using this trick:
http://mhuntdesign.com/blog/jquery/change-default-jquery-version-wordpress/

Hope this helps someone else out there.

Gabie  •  April 13, 2012 11:05

Same problem as Alberto. It stays fixed on top as soon as I scroll. I have 500px image before my navbar and still can't find the problem. It works fine of Firefox, but it does this on Google Chrome & Safari.

Someone please help :D

Masum  •  April 19, 2012 13:25

Thanks, for shared this demo menu

Masoud  •  May 16, 2012 18:19

Hi,
Thank you for this tutorial

Nikos Tsaganos  •  June 4, 2012 12:44

Thanks for all the comments!

Regarding some issues mentioned above, I couldn't reproduce them. I tried the demo with the latest jQuery 1.7.2 and it works. It also worked normally for me under Firefox/IE/Chrome/Safari with a header of 1000px. If you still have trouble with this, please share a link to see if I'm able to help :)

Felix Stekolshchik  •  June 17, 2012 02:03

Hey so first off, great demo and thanks so much for making this.

Ok so i'm trying to center the nav on the demo, and was able to reproduce a centered nav from a site a did a while back, but when i scroll up, it shifts everything to the left. Is there a way to do it so everything just stays centered?

safvanPP  •  July 1, 2012 01:24

nice post thanks for sharing...:)
keep it up
best of luck

giorgos k  •  July 5, 2012 11:05

if (scroll_top > sticky_navigation_offset_top) {
$('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 });
} else {
$('#sticky_navigation').css({ 'position': 'relative' });
}

Lets say I want a new div to appear when position is relative. Is there a better way than:
if (scroll_top > sticky_navigation_offset_top) {
$('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 });
$('#sticky_divtoappear').css({ 'display': 'none' });
} else {
$('#sticky_navigation').css({ 'position': 'relative' });
$('#sticky_divtoappear').css({ 'display': 'block' });
}

matthew f  •  July 19, 2012 14:36

great tutorial! thank you!

it works just great!

I only have one question: how can I change the menu alignment to center or right??

it seems I can't get around this issue...

thanks in advance

M

Chunny  •  August 9, 2012 20:45

Thanks for this bar. I love it. I'd also like to make fixed side navigation bars . That is all three on the same long web page..I've been playing with the code but I cannot get the vertical bars to stay put.. Any advice?

Oliver  •  August 10, 2012 12:20

If you want the navigation to have a fixed-width and be centered, just remove the following code:

, 'left':0

Natarajan  •  August 12, 2012 23:13

I too had the same problem faced by some, where the menu appears to jump "only in Chrome". just figured out that if you have any images, chrome is fast to trigger the $ (DOM ready) function. Just change it to $(window).load which waits for any images to be loaded as well. Hope this helps some one.

zinzinzibidi  •  September 10, 2012 11:03

Thank you dude! I was looking for it =)

Angel  •  September 10, 2012 19:45

Félix Stekolshchik , me pasaba lo mismo, fijate en tu id que personaliste tal vez con otro nombre y agrega allí width:100%, en el ejemplo de la web se llama la id "sticky_navigation"

Otter Creative Studio  •  September 30, 2012 00:42

A.W.E.S.O.M.E. Dude, saved me a lot of time searching for this! Simple, to the point, fast to implement. THANKS! Shared, bookmarked, cherished.

Gopikrishna S  •  October 2, 2012 17:54

I Love You, Buddy!

Satinder Singh  •  October 4, 2012 12:01

Thanks for tutorial..

raman  •  October 9, 2012 13:59

can't we do this with css fixed property ?

raman  •  October 9, 2012 14:00

if yes then please upate this tutorial, because i want my pasges to load faster

sanjeev  •  October 12, 2012 13:56

thanks for a great tutorial.

milky  •  October 20, 2012 05:02

hey all, great tutorial - but I am struggling to implement this into a wordpress site using the 2011 theme... could anyone advise on how i actually go about getting this in wordpress? which bits of code go where? the jquery box all goes in the functions file?
I am a noob in jquery so any help would be appreciated... Simo, maybe you could enlighten me on your integration process...

thanks

NickHarty  •  October 23, 2012 00:06

WONDERFUL tutorial/code. I too had the 'fast-stick problem', where the navigation bar would 'stick' to the top as SOON as I began to scroll.

Solution:
Be sure to specify the HEIGHT of the image/div/whatever ABOVE the navigation bar. This was my problem. I hadn't specified the height of the image above the navigation bar and so the jQuery assumed the image wasn't there.

Thank you!

Icone  •  October 29, 2012 07:05

It has been planned and designed simply but nice. It floats always at the top of the page though you scroll it up and down.

Harikrishna  •  November 4, 2012 10:21

Thank you :) I changed a bit of that code in it and made it appear in the footer, stickied :D Now social icons, search bar and popular posts can be displayed in the footer.

Thanks again :)
Harikrishna

Vaidas  •  November 9, 2012 16:29

Hello,
can anyone just simply say where should be copied jQuery part of code if using the WordPress?
Functions.php?

Thanks in advance..!

David Roberson  •  November 16, 2012 11:03

Every scroll-to-top example I've tried to use on my own site, including this one, refuses to scroll smoothly. When the positon changes from 'relative' to 'fixed' the scrollbar loses focus and stops scrolling. Mousewheel scrolling is interrupted by a little 'hiccup' and keeps on scrolling. It doesn't happen on the demo, but if I copy the same code into my html, it pops up.

Anyone run into this? If so, anyone know how to fix it?

David Roberson  •  November 17, 2012 02:29

I tracked the problem down to a .css conflict in my own menu styles. Earlier in development, something required 'width:100%' to apply an effect to the menu bar. The menu lived inside a wrapper with 'width:100%' and apparently the page renderer trips on the 'inner' width declaration, disrupting the scrollbar event focus. Fortunately, I was able to remove the width declaration from the menubar without disturbing layout.

Jguiss  •  November 19, 2012 11:10

Nice tutorial thanks for sharing :) I was looking for this to implement it on my website !

Lauren  •  November 19, 2012 21:29

I agree with Vaidas - where would you copy and past the jQuery code in a Wordpress site? In the header file, or in the fuctions.php? I would assume it may need to be altered to work in wordpress. Any help is much appreciated.

Murat  •  November 23, 2012 01:27

Great sharing thank you.Anyone can help me integrate this menu for opencart ?

taylor  •  November 27, 2012 22:59

I could not get your code to work without some kind of weird jumping issue... so I created the following... please note that I'm a bit of a jQuery tard, so forgive if I'm wrong when saying that the following code may work better, and it's much cleaner.

$(window).scroll(function () {
if ($(this).scrollTop() > 148) {
$('.sub-header-wrap').css({ 'position': 'fixed', 'top':0, 'left':0 });
} else {
$('.sub-header-wrap').css({ 'position': 'absolute', 'top':148 });
}
});

ฟังเพลงออนไลน์  •  November 28, 2012 07:16

jQuery part of code if using the WordPress?

LosDobos  •  December 1, 2012 00:46

The best place to put the function code would be in a child theme, so you don't lose it when you update. As best I can understand you need to call your jQuery from functions.php, so you make an empty functions.php file inside your child theme folder (same place you have style.css). You then need to put a function into your functions.php file to register and enqueue your script. Here's the code I'm using:

Now create a folder called "js" in your child them folder (where functions.php is). Inside that new folder create a file called "custom_script.js" and paste the jQuery into it.

In theory that should work...

LosDobos  •  December 2, 2012 02:55

gonna try to get that code pasted again...

start php tag goes here
if ( !is_admin() ) { // instruction to only load if it is not the admin area
// register your script location, dependencies and version
wp_register_script('custom_script',
get_bloginfo('stylesheet_directory') . '/js/custom_script.js',
array('jquery'),
'1.0' );

// enqueue the script
wp_enqueue_script('custom_script');
}
end php taggoes here

L. Mercury  •  December 8, 2012 07:35

OH MY GOD, THANK YOU SO MUCH.

I have been banging my head for the past three hours with the "stickyfloat" script. This was the perfect, most painless solution.

Thank you so, so much.

Julia  •  December 14, 2012 17:48

Anyone know how to hide the popup until the point when it sticks to the top of the window?

Thanks, this is a wonderful demo!

Odnel  •  December 15, 2012 23:01

I just was curious if anyone knew how to move the menu container down a little. I have tried so many things and it moves down but after i scroll it moves down again instead of being on top.

Justin  •  January 1, 2013 04:49

Julia - I was able to do it using code like this...

if (scroll_top > sticky_navigation_offset_top) {
$('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 });
$('#sticky_navigation').css("visibility", "visible");
$('#sticky_navigation').css("display", "block");
} else {
$('#sticky_navigation').css({ 'position': 'relative' });
$('#sticky_navigation').css("visibility", "hidden");
$('#sticky_navigation').css("display", "none");
}

pipicom  •  January 2, 2013 17:01

Helpful and straightforward tutorial, thanks!

laura  •  January 19, 2013 05:12

I'm creating a site in dreamweaver (my first) and i'm attempting to implement the stickynav by pasting each of the codes in, but the nav doesn't stick when i preview the site in safari 6 or chrome. i haven't changed anything about the codes, and the demo works just fine. any ideas what i might be doing wrong?

thanks!!

laura  •  January 19, 2013 05:58

nevermind, i figured it out!

Saliem  •  February 3, 2013 05:24

Anyone planning to turn this into a plugin?

Sanjay  •  February 7, 2013 05:58

wow brilliant nice work i really appreciate this. keep it up.

Ramsay  •  February 17, 2013 19:12

Thank you for this detailed tutorial. I'm planning to use .animate jQuery property instead of .css, so that a smooth animation effect will be displayed.

Allison  •  February 24, 2013 02:51

This tutorial was clear even for someone who has never used jQuery before. Thanks for putting it up!

Rohan Shewale  •  February 24, 2013 14:13

Quite simple tutorial, I like the way of presentation.
Thanks for the help..!

naresh  •  February 26, 2013 23:05

the download version is not working in IE 9, can you please help me to fix this.

csslove  •  February 28, 2013 17:28

Hi, that not work in IPad

shanu  •  March 2, 2013 03:43

its very helpful... thkz

Nuzree  •  March 23, 2013 06:48

Thanks a lot for the great tutorial, was looking for a nice clean tutorial, this was the perfect match,

Have a nice day.

All the best. !

Tobias Redmann  •  March 25, 2013 16:21

This is nice and easy. I use it now on http://www.handy-preis.net . The price box always stays on top of the page.

KPCTA  •  April 8, 2013 00:31

Great tutorial, but help us how to solve isue with wordpress theming. Where to put jquery code. In Header file not working.

Thank you in advance.

Webdesign Soest  •  April 8, 2013 15:32

Where can i define the height of fixing?

quangpd  •  April 12, 2013 08:02

Thank so much.
It helpful with me :)

Babaroga  •  April 19, 2013 23:37

How can i implement this in my joomla website?

Roselle  •  April 21, 2013 10:57

You're awesome! I've been looking for this tutorial for hours! Thank you so much!

I have 2 questions:
1) how can I make whatever I've positioned to always stay on top? some pictures and facebook buttons show up over whatever is fixed;

and

2) how can I change the css of whatever's fixed? for example, my main nav is fixed, when it moves down, I want to change the background color. Is this possible?

Thanks a bunch!
Roselle

Oscar  •  April 29, 2013 22:01

Where would the 'z-index' go? on the CSS or Jquery file?
Under what line?
Your help is much appreciated.
Regards,
--------------------------------------------------------------------------------------------------------------
patrioticcow • April 5, 2012 22:57
nice. some people ,mighty want to add 'z-index': 100000 so the menu will stay on top of any image sliders or whatever.

Ngan Tengyuen  •  June 4, 2013 18:07

if you're using Wordpress. You might find my plugin just what you've been searching for. I've created a sticky header bar for Wordpress. Do check it out - http://www.geckoandfly.com/fbar-social-wordpress-plugin/

Sponsi  •  June 10, 2013 18:41

No luck, the navigation bar just turns into left. Deleting left: 0 doesn't help. I guess it's because it's fixed. This sucks, though. It makes the script totally unusable.

Tarsem Singh  •  June 20, 2013 11:38

Wow nice information :)

sathish  •  June 25, 2013 12:47

its really good job :)
Thanks and regards
sathish

Banu  •  July 3, 2013 13:37

Hello,
Thank you so much for the information. I need your help. I added a Facebook like button on my site. However when you click it , it shows your content. This is very clever of you and great thinking but I would appreciate if you help me change this information with mine. I am just using your script on my website which is basically fine art.

Ziyaddin  •  July 24, 2013 07:34

Thanks, very much, helped me!

Hegin  •  July 24, 2013 17:32

I can't view this in IE8. Why?

Sebastian  •  July 25, 2013 19:20

how use it in wordpress??

rheeantz  •  September 7, 2013 23:41

same question, how use it on wordpress theme

Mavuso Mabhula  •  September 13, 2013 23:31

Great share, much appreciated...

Astro Complex  •  October 25, 2013 22:56

Thanks for sharing such knowledge, I did incorporated this code to my other websites.
it looks good and it gives easy access to menu.

more power to you Mr. Nikos

HeroWP  •  November 6, 2013 04:55

Amazing tutorial. I can't wait to make my menus sticky, on my upcoming wordpress themes. Cheers mate!

Pete  •  November 22, 2013 22:09

Rad. Cheers dude.

Ganyos  •  January 16, 2014 13:42

For someone who ask, where to put z-index: 1000;, you can put it on the css style.
I tried to put it on all css style, on the last part and it work.

Josef Meile  •  January 19, 2014 17:11

Thanks for the code. It helped me a lot.

asim  •  January 26, 2014 15:40

It's work....Thanks

طراحی وب سایت در اصفهان  •  May 30, 2014 17:50

as some people told :
i can not undrestand this .
pleas discribe it
Julia - I was able to do it using code like this...

if (scroll_top > sticky_navigation_offset_top) {
$('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 });
$('#sticky_navigation').css("visibility", "visible");
$('#sticky_navigation').css("display", "block");
} else {
$('#sticky_navigation').css({ 'position': 'relative' });
$('#sticky_navigation').css("visibility", "hidden");
$('#sticky_navigation').css("display", "none");
}

Kristina  •  June 3, 2014 17:47

Does anybody else get an error saying Undefined is not a function

chat  •  June 10, 2014 17:57

Wery nice navigation menu but this jquery coding not working extra pluging ?

obat kuat  •  June 24, 2014 11:59

seorang istri lebih menginginkan ketika hubungan suami istri sama pasangannya bisa lebih puas dengan ereksi yang lebih keras, kencang dan juga tahan lama, seorang dokter lebih menganjurkan anda untuk meminum obat kuat herbal alami yang ampuh mengatasi lemah syahwat dan ejakulasi dini serta bisa menyembuhkan secara total.

Cindy  •  July 4, 2014 15:00

thanks for this tutorial. it was very helpful and it kind of worked. but still i have a little problem... may anyone help me? i'm creating a small website for an exam at university.

when scrolling down the page, there is a gap of about 15px between the navigation and the top of the page. (i already set the margin of the page (body) to 0px all around.)
so i set the value of position fixed top to -15px that it actually sticks to the top. but as soon as i scroll back to the top of the page, there is a gap between the navigation and the header of about 15px.
any ideas?
(first comes the navigation, then the header, then the content.)

bryan kimani  •  August 1, 2014 10:23

This code is very helpful to me. Worked like magic.

طراحی سایت  •  August 1, 2014 15:44

tanks
because this code very good for me

banwari chouhan  •  August 4, 2014 07:36

Thanks
Awesome Tutorial

paul  •  August 18, 2014 07:35

i tried using your code but my problem arise when i put a picture.. the picture overlaps the navigation bar... what should i do?

Mehul Mali  •  August 28, 2014 11:03

Thanx,
nice
really helpful me.

Post your comment

(optional)
(optional, will not be shown)
NOTE: Any links will have rel="nofollow"

back