How to Create Active Menu?
When we’re creating a navigation menu for a website, it’s always good to make it so the visitors or user on the website knows on which page or part of the site he is on. This can be accomplished by adding an “active class” or “current class” to the menu item that links to the page on which the visitor or user is. With the help of this coding you can make the different menu active on different page without changing the code in every page for future use just make changes at one place and other page’s menu will automatically change.
To do this, we’ll create a CSS navigation menu. With a few links in it just for demonstration. Of course you can add as many as you want.
HTML Code
Paste the below in HTML file:
<body>
<div class=”container”>
<nav class=”navecation”>
<ul id=”navi”>
<li><a class=”menu active”#”>About </a></li>
<li><a class=”menu” href=”#”>Contact </a></li>
<li><a class=”menu” href=”#”>Services</a></li>
<li><a class=”menu” href=”#”>Contact Us</a></li>
<li><a class=”menu” href=”http://www.mywebtricks.com/2014/03/add-active-class-to-navigation-menu.html”>Read Our Blog</a></li>
</ul>
</nav>
</div>
<body>
CSS Code
Paste the below code in CSS file:
body{
font-sze:14px;
}
.container{
max-width:960px;
margin:0 auto;
}
nav ul li{
list-style:none;
float:left;
padding-right:20px;
}
nav ul li a{
text-decoration:none;
color:#222;
background-color:#ccc;
padding:10px 20px;
}
.active{
background-color:#d90000;
color:#fff;
}
JQuery Code
Paste the below in JQ file:
$(document).ready(function(){
$(‘ul li a’).click(function()
{
$(‘li a’).removeClass(“active”);
$(this).addClass(“active”);
});
});