Tam Nguyen Photography

New York Beauty and Fashion Photographer

Using jQuery to Dynamically Set a Static Top Navigation Menu

Posted on April 20, 2013 in Technology, Tips

Using jQuery to Dynamically Set a Static Top Navigation Menu

The post title is a bit confusing, so I’ll try to explain the purpose here: Let’s say you have a webpage with a top navigation menu. Now, suppose you want to be fancy and have the top navigation stay static with respect to the page as the user scroll down. The effect is seen implemented on sites like Facebook, Twitter, Google, Techcrunch, Woot.com, etc… I’m going to explain how this trick is done using ¬†jQuery. Now, I’m not a huge fan of using Javascript to design a website, but there are things that can only be done using JS. You should know that eyecandy like this should come after the design. The site must work even if JS is disabled.

The logic goes something like this:

– First, your navigation bar should have a name.
– Using jQuery, detect the browser window to see where the user is with respect to the top of the page.
– If the user has scrolled passed a certain point, use jQuery to add in a CSS class, let’s call it “.fancy”, to the navigation element.
– In your CSS, design your “.fancy” class to position the navigation as “fixed”.
– In your jQuery, make sure you remove the “.fancy” class once the user scrolls up passed the “fancy” point.
– And you’re done.

Here’s the example Javascript code, with my “fancy” point at 90px from the top:

<script type="text/javascript">
	jQuery(function () {
		jQuery(document).ready(function () {
			jQuery(window).scroll(function () {
				if (jQuery(this).scrollTop() > 90) {
					jQuery('#menu-area').addClass('fancy');
				} else {
					jQuery('#menu-area').removeClass('fancy');
				}
			});
		});
	});
</script>

Here’s the example CSS code:

.fancy {
	position: fixed !important;
	margin-top: 0 !important;
	top: 0;
	box-shadow: 0 12px 12px -6px #444;
}

One of the problems I ran into with doing this is that when my top navigation was positioned as ‘relative’ and then when the jQuery added the “.fancy” class to make it fixed, the page kind of jumped a little, because now that the element is no longer there relatively, the rest of the page gets pushed up to fill up that space. It’s somewhat important that your navigation start off with absolute position.

Here’s the live demo on Codepen. Feel free to drop me a line below if you have any questions.

using-jquery-to-dynamically-set-a-static-top-navigation-menu-1

1 Comment

  1. Krzysztof November 28, 2013

    It’s good but i found one problem – if you resize your browser your menu won’t fit – you cant scroll x axis

Leave a Reply

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