Site logo

Archived topic

Smooth Scroll from nav links to sections and highlight current menu item

3 replies · Started by Stefan on August 13, 2018

Viewing posts 1–4 of 4

Hey,
I try to highlight just the current menu item in the sticky header menu, after clicking the link and scrolling down to the corresponding section.
The solution from this topic: "Page scroll to id to highlight current element on sticky nav" didn't worked. But I'm not certain that I implemented it the right way. Just added the script to the footer.

Actually it's just adding and removing the current-item class or?
This script worked somehow but it was a little rickety and using the generatepress script would a better way I think.

I've found out that you are using the smooth scroll script of cferdinandi.
A solution to add and remove classes might be this callback, as I found in a comment:

var scroll = new SmoothScroll('a[href*="#"]', {
	// Callback to run after scroll
	// Anchor is the element you're scrolling to
	// Toggle is the link that triggered the scroll
	after: function (anchor, toggle) {
		// Remove link from previously active link, if one exists
		var current = document.querySelector('scroll-active');
		if (current) {
			current.classList.remove('scroll-active');
		}

		// Add a class to the clicked toggle
		if (toggle) {
			toggle.classList.add('scroll-active');
		}
	} 
});

But it's not working. I've added it to the footer, tried different selectors but I can't get it to work. I'm not sure on how to use the API,too.
Could this be a solution in general or am I totally wrong?

Help would be great!

Thanks in advance,
Stefan

Hi Leo,
pretty neat solution. Works perfect and even has a manual scroll function. That's great.

Initially I thought I could just use a little tweak to your script like the code snippet in the original post.
But maybe it's more complex. So everything is fine now.

From a learning to code perspective. If someone finds the time to have a look why the following snippet is not working even when it's from your script author cferdinandi, would be great.

var scroll = new SmoothScroll('a[href*="#"]', {
	// Callback to run after scroll
	// Anchor is the element you're scrolling to
	// Toggle is the link that triggered the scroll
	after: function (anchor, toggle) {
		// Remove link from previously active link, if one exists
		var current = document.querySelector('scroll-active');
		if (current) {
			current.classList.remove('scroll-active');
		}

		// Add a class to the clicked toggle
		if (toggle) {
			toggle.classList.add('scroll-active');
		}
	} 
});

Apart from that thanks Leo.

Have a nice day!

No problem :)

This archived topic is closed to new replies.