admin管理员组

文章数量:1405608

I'm trying to use javascript / jQuery to highlight the current pages list item on my main menu. I am new to scripting and can't work out what the problem is. Here is the code i've been trying with.

<ul id="#mainMenu">
    <li><a href="/home">Home</a></li>
    <li><a href="/about">About</a></li>
    <li><a href="/contact">Contact</a></li>
</ul>

<script type="text/javascript">
$('#mainMenu li a').on('click', function(){
    $('li a.active').removeClass('active');
    $(this).addClass('active');
});
</script>

I'm trying to use javascript / jQuery to highlight the current pages list item on my main menu. I am new to scripting and can't work out what the problem is. Here is the code i've been trying with.

<ul id="#mainMenu">
    <li><a href="/home">Home</a></li>
    <li><a href="/about">About</a></li>
    <li><a href="/contact">Contact</a></li>
</ul>

<script type="text/javascript">
$('#mainMenu li a').on('click', function(){
    $('li a.active').removeClass('active');
    $(this).addClass('active');
});
</script>
Share Improve this question asked Aug 20, 2015 at 9:49 TomTom 451 silver badge4 bronze badges 1
  • I presume you've added the extra CSS for the elements with the class of active? – Jay Commented Aug 20, 2015 at 9:53
Add a ment  | 

2 Answers 2

Reset to default 7

If you're happy to add the class to the menu based on the current URL in oppose to using the .click function then I have a solution for you.

$(document).ready(function(){
    $("a[href*='" + location.pathname + "']").addClass("active");
});

On page load. This pares all the anchor tags on the page to the current URL. And if they match. Adds the class of .active to the element.

I want to add to the accepted answer by Jay. Sometimes your URL may be 'posts' for a menu item and 'posts/create' for another one. So code from accepted answer will highlight both. To avoid that, do the following: use window.location.href instead of location.pathname and remove * after href:

$(document).ready(function(){
    $("a[href='" + window.location.href + "']").addClass("active");
});

本文标签: javascriptHighlight current page on main menuStack Overflow