It’s been a while since I posted tutorial article. In this post, I will show you how to create a smart sticky navigation bar easily with just few lines of Javascript codes, powered by the mighty jQuery.
Smart sticky navigation bar is a bar that sits at its original place above the fold, but when you start scrolling down the long page, it will sticks at the top of the browser window and follows, similar to IGN’s corporate website’s navigation bar. Continue reading out the demo and the codes after the break.
Demo
Check out the demo! It works on most modern browsers.
Tutorial
For this tutorial, we are going to use HTML, CSS and jQuery. The HTML structure is fairly simple, the most important thing is to have a header, the navigation bar and the content area below the navigation bar. Everything wrapped in a div id called “wrapper”.
HTML
<div id="wrapper">
<header>
<h1>Simple Smart Sticky Navigation Bar</h1>
</header>
<nav>
<p>Navigation Content</p>
</nav>
<div id="content">
<p>Website content here.</p>
</div>
</div>
CSS
Here are the important CSS rules to style up the page. For the navigation bar, I used the artwork from 5 stylish navigation bars which was created by me.
#wrapper {
width:940px;
margin: 0 auto;
}
header {
text-align:center;
padding:70px 0;
}
nav {
background:url(img/nav-bg.png) no-repeat;
height: 60px;
width: 960px;
margin-left: -10px;
line-height:50px;
position: relative;
}
#content {
background: #fff;
height: 1500px; /* presetting the height */
box-shadow: 0 0 5px rgba(0,0,0,0.3);
}
.fixed {
position:fixed;
}
Notice that I added the “fixed” class which we will going to use it in jQuery code.
jQuery
At first we need to have the jQuery file. Grab it from jQuery official site or copy paste via scriptsrc.net, then paste it at the bottom of the HTML file before the end of body tag. Then include the javascript code below within another script tag:
$(document).ready(function() {
//Calculate the height of <header>
//Use outerHeight() instead of height() if have padding
var aboveHeight = $('header').outerHeight();
//when scroll
$(window).scroll(function(){
//if scrolled down more than the header’s height
if ($(window).scrollTop() > aboveHeight){
// if yes, add “fixed” class to the <nav>
// add padding top to the #content
(value is same as the height of the nav)
$('nav').addClass('fixed').css('top','0').next()
.css('padding-top','60px');
} else {
// when scroll up or less than aboveHeight,
remove the “fixed” class, and the padding-top
$('nav').removeClass('fixed').next()
.css('padding-top','0');
}
});
});
Well that’s it! Please check out the demo to see the result and view the source code! Personally I think scrollTop() is a very useful when dealing with scrolling, it can be used in many simple yet useful functions. I hope you learn something from this tutorial!
Credits:
Background texture from Subtle Patterns | Font from Google Web Fonts
Comments