My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a small issue where the Home button is always highlighted along with the current page's menu item. For example, when viewing the "Archive" page, both Archive and Home buttons are highlighted.
Just so you know, I am using Wordpress to build my website and I know that Wordpress supports this effect. However, I would like to achieve this without relying on Wordpress.
This is the HTML code:
<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>
And here is the JS code:
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 must admit that I'm not very familiar with javascript, so there could be some mistakes in the code.
Thank you for taking the time to read this, and I wish you a fantastic new year!