简体   繁体   中英

How to Add Active Class to a Navigation Menu Based on URL in each page

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>

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;
}

WORKING EXAMPLE

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM