If you want to make your navigation menu or any other box stick to top on scroll then let me tell you, you are at the right place ;-)
Yes, you can make your navigation menu or any other box like ‘ad box’ sticky easily with just few line of easy code. You just need to add few line of Javascript and CSS as per your design.
Every time you scroll the browser window, the Javascript checks if the navigation box is in the view port or not. If the navigation box is not in the view post then it adds a CSS class ‘stick’ in the navigation box. Now its time for some CSS like ‘position:fixed; top:0;’. Thats it, you have your own sticky navigation menu or ad box :-)
Okay, here is the javascript code:-

1
2
3
4
5
6
7
8
9
$(document).ready(function(){
	var a={id:"sticky","class":"stick",offset:0};
	var b=$("#"+a.id);		
	a.offset=b.offset().top;		
	$(window).scroll(function(){
		var c=$(window).scrollTop();
		c>=a.offset?(b.addClass(a["class"])):b.removeClass(a["class"]);
	});
});

You can replace the id ‘sticky’ in the code with your navigation wrapper. Also if you want some other CSS class to be added then replace the class ‘stick’ with your own CSS class.
Don’t forget to add jQuery before this script.

Not its time for some CSS:-

1
2
3
4
.stick{
	position:fixed;
	top:0;
}

Remember you can replace this CSS class with your own class.

And yes, we are done here.. En joy your sticky navigation menu.

One Response so far.

  1. dharam says:

    Great job Man….!!!!
    I have searched a lot for this functionality…

    Thanks