So basically I'm trying to give a class "current" to highlight the menu item for the current page.
I've tried a couple of snippets I've seen on this website but most of them didn't work. This code is almost working for me, but the problem is although the current menu item is properly highlighted, Home button is also highlighted no matter which page I'm viewing. So like if I'm viewing "Archive" page, both Archive and Home are highlighted.
I'm using Wordpress to build the website by the way and I'm aware that Wordpress supports this effect but I'd like to achieve this without it.
HTML
<ul class="navigation">
<li><a href="<?php echo home_url() ?>" class="navItem">Home</a></li>
<li><a href="<?php echo home_url(/archive) ?>" class="navItem">Archive</a></li>
<li><a href="<?php echo home_url(/about) ?>" class="navItem">About</a></li>
</ul>
JS
jQuery(function($) {
$('.navigation li a').each(function() {
var target = $(this).attr('href');
if(location.href.match(target)) {
$(this).addClass('current');
} else {
$(this).removeClass('current');
}
});
});
I'm not really familiar with javascript so there might be some errors.
Thank you for reading this, and have a great new year.
question from:
https://stackoverflow.com/questions/65516730/highlight-the-current-menu-item 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…