How to set navigation element "current" state for subdirectories

Hi folks,

I have a navigation link to “/blog” where all my blog posts are listed.

When I click on that link the navigation element gets the “w–current” class and therefore looks bold for instance.

Now when I click on one specific blog post I land on a subdirectory url like “/blog/my-blog-post” but the “w–current” class is gone from the navigation blog link.

I managed to fix that now by adding a js-script to the footer:

window.addEventListener("load", (event) => {
	let currentUrlPath = window.location.pathname;

	Array.from(document.getElementsByClassName('navigation-item w-nav-link')).forEach((el) => {
      	let elUrlPath = el.getAttribute('href');
          if (currentUrlPath.includes(elUrlPath)) {
          } else {

But since this is waiting for the document to be loaded it has a small delay.
So I’m not really happy with that solution.

Isn’t that also possible native by Webflow?

There is no native solution, however you can position your script right after the navigation element. Javascript can access any DOM that’s been parsed up to that point, so place an HTML Embed immediately after the nav bar.

You’d remove the addEventListener wrapper, since you don’t want to wait for the full page load to complete.

1 Like

Thanks for you reply.
That quite worked, but I sill needed to put the code inside a setTimeout with 100ms delay, otherwise it didn’t worked…

Hmm, this approach, also with the setTimeout of 100ms, is not reliable.
Sometimes it’s working, sometimes not. I also increased the timeout to 300ms but same effect.

I go back to the window.load callback :wink:

What is the code you had previously following your menu item, before you added the delay?