Add class to currently selected page on my navigation?
Is there a way to add a class to the page you're currently visiting in the menu?
Yes! You can take advantage of the {{active}}
property of items in your site's {{#menu}}...
, like so for example:
{{#menu}}
<a href="{{{url}}}" class="{{active}}">{{label}}</a>
{{/menu}}
Answered 2 years ago ·
Edit answer
Is it possible to make this work for a tagged page that is in the menu? For example mysite.com/tagged/foo and the link in the menu is Foo. Right now it does not receive the active class.
Answered a year ago · Edit answerYou could do that with JavaScript, like so:
// Add class for active menu links
$('.header a.menu')
.filter((i, el) => $(el).attr('href') === location.pathname)
.addClass('is-active')
Anecdotally, when doing a ?json=1
view I don't see an active
key available in the menu
.
The comparison made by {{active}}
is quite naive at the moment. I need to make it more tolerant of query strings and full-qualified URLs