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
2 Answers
Reset to default 7If 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
版权声明:本文标题:javascript - Highlight current page on main menu - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744335195a2601155.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论