How To Create Sticky Navigation Bar

jquery_banner

In last week, one of our clients asked us to develop a sticky navigation bar for his website. Such navigation or menu bars are pretty much used by every website. You may have noticed the menu bar which sticks to the top of the webpage or move along the page while you scroll down. Making a sticky header or any container which is already on the top of the page is not a big deal. All you need to do is apply fixed position to that container, it will become sticky and always remains on top, but situation becomes tricky if navigation bar is below header and you want to make it sticky after placing it on the top after when user scrolls down the page and header disappears. The Image below will help you to understand the task.

Above image is clearly defining our goal which is in short to place the navigation bar on top and make it sticky after user scrolls down and header disappears. For demo lets prepare a dummy html web page which will have the header, below header there will be a navigation bar and then there will be a content container with dummy content and a fixed height to create a scroll on the page. Here is the HTML and CSS or our dummy webpage.

<div class="header"><strong>Header</strong></div>
<div class="nav"><strong>Navigation Bar</strong></div>
<div class="content"></div>
<style>
body{
	margin: 0;
}
.header{
	height: 50px;
	background-color: #000;
	font-size: 16px;
	text-align: center;
	color: #fff;
	padding-top: 3%;
}
.nav{
	height: 30px;
	background-color: #D7D7D7;
	font-size: 16px;
	text-align: center;
	color: #000;
	padding-top: 5px;
	width: 100%;
}
.content{
	height: 1200px;
}
</style>

I guess the HTML and CSS is pretty straight forward, self explanatory and very easy to understand. Now, lets start thinking about the solution of our problem. Obviously we are going to use jquery to get our desired result. As you might have figured out that we will target the scroll event of DOM (Document Object Model) to trigger our jquery code for making the navigation bar sticky. As, we need to make the navigation bar sticky when user scrolls down and the header container will disappear so we also need to measure the scroll height. Okay, now lets start coding the action part which is coding the jquery.

<script type="text/javascript">
$(document).ready(function (){
	$(window).scroll(function() {
	}
}
</script>

The first line of code might seem very familiar if you have used jquery before, in this code you are selecting the whole document and then you will apply firing a function on ready event which will let you to execute your jquery when the webpage or document is completely loaded. In the second line we are again selecting the window and firing function on its scroll events. That means whatever we write between this function will be fired on the scroll event. Now, before proceeding forward we need to determine the scroll length from top when header disappears from the screen. We can either find it by the jquery function scrollTop() which will also be our key option or by measuring the length of our header container. You can also refer to Measuring user scroll with jquery.

In our case the value of scroll top is 90. So what we are going to do is to check the length of user top scroll if the length of user scroll  becomes greater or equal to 90 we will apply CSS to place the navigation bar on top and make it sticky. We can also use jQuery toggleClass function to change the CSS of navigation bar but I am comfortable doing it with jquery.

$(document).ready(function (){
	$(window).scroll(function() {
		var scrollTop = 90;
		if($(window).scrollTop() &gt;= scrollTop){
			$('.nav').css({
				position : 'fixed',
				top : '0'
			});
		}
	}
}

Once you have added the above code, the moment you will refresh the page, and scroll down your page as soon as the header will disappear from the screen navigation?? bar will be placed on top and it will move along the page, but if you scroll back on top you will notice that the navigation bar will remain on top of the page above header and we obviously don’t want to mess with the user experience. So we will apply another check on top scroll of the DOM and when it will become smaller than 90 we will simply remove our additional CSS. Here is final shape of our jquery code.

<script type="text/javascript">
$(document).ready(function(){
	$(window).scroll(function(){
		var scrollTop = 90;
		if($(window).scrollTop() >= scrollTop){
			$('.nav').css({
				position : 'fixed',
				top : '0'
			});
		}
		if($(window).scrollTop() < scrollTop){
			$('.nav').removeAttr('style');	
		}
	})
})</script>

Do give us Feedback on this by leaving comments below and if you want us to help you with anything or if you have suggestions. Let us know and we’ll be more than happy to assist. Enjoy and keep coding!

View Demo


Tags:  , , , , ,

By Umair Abid

Hi, My name is Umair Abid currently working at Coeus Solutions GmBH as PHP Developer. Feel free to connect with me on Twitter, Linkedin, Github and Facebook.

More By Umair

  • zend-framework-2
  • yahoo-answers
  • php-notifications-system
  • images
  • wordpress_with_adsense
  • php
  • Web Development
  • images

21 thoughts on “How To Create Sticky Navigation Bar”

  1. Dan Allen says:

    Hi Umair,

    great article and one of the most simple sticky navs I have seen. I was looking to use this on the menu that has a dropdown megamenu. When i use this code the dropdown function on the menu does not work . Is that common with these type of navigation menus?

    Regards,
    Dan

  2. Umair Abid says:

    Thanks Dan,
    Everything in the nav div should be moving along but its hard to figure out the problem without having look at the code. :)

  3. Naveen says:

    Hi,

    The code works great in IE and Chrome, the dumb IE makes it break the layout.

    I’m using a dropdown menu in it, but while scrolling in IE the menu moves ti right. I believe there is a z-index problem which I am not able to resolve.

  4. Naveen says:

    I mean firefox not IE .. it dosent work in IE

  5. Umair Abid says:

    Can you show me your code Naveen?

  6. Leroy says:

    Wow. Nice and simple. Definately using this..

  7. Surjith SM says:

    here is an interesting approach to Sticky navigation, Only shows navigation when user really wants to be.. http://web3canvas.com/item/sensitive-sticky-navigation-with-jquery/

  8. Umair Abid says:

    Good tutorial but I guess you only show the navigation bar when user scrolls up, what if? if user scrolls down and look for the nav bar?

  9. James says:

    Great just what I was looking for I will bookmark this page for when I finish the design stage.

  10. Dave says:

    Can this be used for custom menus on wordpress themes?
    Thnx

  11. Jeff says:

    how would I do this with a top that is dynamic (ex: not always 90)

  12. Umair Abid says:

    Place your dynamic content in the navigation container

  13. Christine says:

    $(document).ready(function(){
    $(window).scroll(function(){
    var scrollTop = 632;
    if($(window).scrollTop() >= scrollTop){
    $(‘#navigation’).css({
    position : ‘fixed’,
    top :’0′
    });
    }
    if($(window).scrollTop() < scrollTop){
    $('#navigation').removeAttr("style");
    }
    })
    })

    The .removeAttr isn't working for me. :( The rest of it is though. This is exactly what I need, just need that second part to work. Any tips?

  14. Umair Abid says:

    Which browser you are using?

  15. Christine says:

    I am using Chrome. I see that it works in Mozilla, any tricks to help it work in Chrome?

  16. Taz says:

    Hello,
    Thank you your the tutorial. This is strange since it doesn’t work on my local testing. I’ve putted everything like you but noting happens.
    Testing on Safari and Firefox with PHP5 on local.
    T

  17. JOHN says:

    Hello,

    Doesnt work in IE8. I have treid to edit but still doesnt works. any updates?

  18. IE 8 Fails says:

    It does not work on IE 8. Do you know if there is another library of JQuery that works for IE

  19. shaunveto says:

    I have a similar question as above. When I add this to my site it jumps to the left and the drop down menus stop working. My site is not published yet but I am willing to send you my code if you wouldn’t mind looking at it. I’ve tried multiple different types of stickies like this and get the sam result every time. Thanks.

  20. Umair Abid says:

    Send your code at umairabid.dev@gmail.com, also let me know which browser you are using

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv badge