How to make navigation menu sticky

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:-

$(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:-

.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.

Comments

Leave a Reply

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

Privacy Policy ยท Contact ยท Sitemap

ยฉ 7Tech – Programming and Tech Tutorials