Update nav-current when linking in a page

I am wanting to update nav-current when linking within a page. I have tried using bootstrap scrollspy, but this doesn’t work when using {{navigation}}.

It seems that when coming from another page on the site, it doesn’t register the full url https://example.com/#about, and only wants to work with /#about.

Any ideas on how to fix this?

Hey @Izak_Jackson :wave:
I think this is because anchor links are internal to the page, which means the server isn’t aware of the anchor link. It would be best to use some JavaScript to highlight the internal anchor link. Here’s some code I’ve put together:

// Get all the links that are internal hash
const allAnchorLinks = document.querySelectorAll(`a[href*="#"]`);

// Function to check if any link matches the hash in the current URL
const checkURL = link => {
	if (link.hash.substr(1) === window.location.hash.substr(1)) {
		link.classList.add("nav-current");
	} else {
		link.classList.remove("nav-current");
	}
}

// Cycle through the internal hash links, run check function on load and whenever the hash updates
allAnchorLinks.forEach(link => {
	window.addEventListener('hashchange', () => checkURL(link));
	checkURL(link);
});

Here’s a demo on CodePen too https://codepen.io/daviddarnes/pen/bGdoozK?editors=0011

Let me know how you get on with this :slight_smile:

1 Like

Brilliant, thank you! I’ll give this a try

1 Like

Worked perfectly, thanks!

1 Like

Just noticed this doesn’t update when scrolling down the page (I’m needing it to update when scrolling past sections with that id). I have tried updating the hashlink when scrolling, but this then prevents the user from scrolling back up.

Any ideas on what I could do to add this functionality?

It would require adding more javascript. Are you sure these sections can’t be their own pages? If not have to seen our tutorial on adding a table of contents? Sounds like you’re trying to achieve something similar: