Log in Sign up

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?


10 months ago, 4 replies   developers   menu   active   Edit question

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 10 months ago · Edit answer

You 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.

Answered 10 months ago · Edit answer

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

Answered 10 months ago · Edit answer