About

Labels

slider

Recent

Navigation

Create a sticky navigation displayed after scroll using Javascript

Navigation often stays below header and pages are sometimes too much long that user get out of reach from navigation. The reason developer sticks the elements to screen is to give availability of elements across the page. Navigation bar contains some of the most clicked links of the site, so we need to make it available every time user needs it. Have a look at demo below:
See the Pen Sticky nav by Mohammad Hamza Dhamiya (@hamzadhamiya) on CodePen.
We are using Waypoint JS, a no framework version to avoid using jQuery. This plugin helps when we want to add some class when we scroll through some element. Like in above pen, as you scroll to main content navigation bar appears. Well, this is not just because waypoint js but CSS frame rule too.

Things start by adding a friendly markup. I wanted to show up the title with navigation so I just added a link of title in navigation tag.
<nav>
<a href='#' class='nav-title'>Santa Work Shop</a>
<ul>
<li><a href='#'>Home</a></li>
<li><a href='#'>Contact</a></li>
<li><a href='#'>About</a></li>
<li><a href='#'>Work</a></li>
</ul>
</nav>
Before scrolling to main content it remain hidden due to max-width is set to 0 and overflow is hidden. As we scroll to main content, waypoint js adds a class in navigation bar. 
var waypoint = new Waypoint({
element: document.querySelector('main'),
handler: function(direction) {
var nav=document.querySelector('nav');
if(direction == "down"){
nav.classList.add('stickit');
}
if(direction == "up"){
nav.classList.remove('stickit');
}
}
});
Now as we scroll down, class is added and when we scroll upward, class is removed. Now we can customize the navigation according to stick position and normal position. What makes it sticky is the position attribute.
nav.stickit{
position:fixed;
width:100%;
animation:stickit 300ms;
top:0;
}
@-webkit-keyframes stickit {
0% {top: -50px;}
100% {top: 0px;}
}
@keyframes stickit {
0% {top: -50px;}
100% {top: 0px;}
}
To create that dropping effect of navigation, I used keyframe for it. Hope that helps cheers.
Share
Banner

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: