Reputation:
i have a navigation menu on top of my website .that li's content many pages with different urls. How to Add Active Class to a Navigation Menu Based on URL that in each page display it with a specific color?
<ul>
<li class="red"><a href="home">HOme</a></li>
<li><a href="gallery">gallery</a></li>
<li><a href="about">about</a></li>
<li><a href="contact">contact</a></li>
</ul>
Upvotes: 0
Views: 4051
Reputation: 50291
This snippet will be useful
HTML
<ul id="menuList">
<li><a href="home">Home</a></li>
<li><a href="gallery">gallery</a></li>
<li><a href="about">about</a></li>
<li><a href="contact">contact</a></li>
</ul>
JS
$('#menuList li').click(function(e){
e.preventDefault(); //Remove this in your main code
$('#menuList li').removeClass("active");
$(this).addClass("active");
});
CSS
.active{
background-color:green;
}
Upvotes: 2
Reputation:
Give a class or ID to the ul
. Then, assuming jQuery and an ID of nav
:
$(function() {
$('#nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});
All you need then is to style the .active
class. Also, this assumes your links are /my-page
, so if you are currently in my-page
, the link will become .active
.
Upvotes: 0