Activate Menu Items by Scrolling / Anchorscroll
-
Hello everybody,
Did any of you try and succeed making active Menu items (anchors) visible when scrolling down on the site? Like on this website here: https://make.studio/de/
By scrolling down, the currently visible section of the page is highlighted in the menu via an underline. I've read about JavaScript like ScrollSpy but haven't been able to comprehend its implementation. I feel like this could be a useful addition to the theme, though.
I'd be happy for any guidance in the right direction!
xx -
Ok, so to whom it may concern, I've found a solution with a little script:
<script> jQuery(function ($) { $('nav a').addClass('menu-active') $(window).scroll(function () { var scrollPos = $(window).scrollTop(); $('.menu-section').each(function (i) { var topPos = $(this).offset().top; if ((topPos - scrollPos) <= 80) { $('.menu-active').removeClass('menu-active') $('nav a').eq(i).addClass('menu-active') } }) }); }); </script>
and according CSS, which can of course be dealt with as you please:
nav a.menu-active { color: red; }
To me, it seems nice and clean, but maybe some of you have suggestions how to make it more elegant? It might be a useful feature for future updates, including this as a setting where the other Anchor settings are.
-
I forgot to add that you have to give the according rows on the site an ID, in this case it is "menu-section". So basically your rows will have to have an ID and CLASS for the effect and anchor to work.
The only thing that I haven't been able to work out is the situation that on load of the page, all links in the menu will be activated at once. I believe though that this is solvable by including the first header element into the variable ... not sure though.
EDIT: Just delete the first variable and that's it
$('nav a').addClass('menu-active')
Before you post:
- When using a WordPress Cache plugin, disable it or clear your cache.
- Update Lay Theme and all Lay Theme Addons
- Disable all Plugins
- Go to Lay Options → Custom CSS & HTML, click "Turn Off All Custom Code", click "Save Changes"
This often solves issues you might run into
When you post:
- Post a link to where the problem is
- Does the problem happen on Chrome, Firefox, Safari or iPhone or Android?
- If the problem is difficult to explain, post screenshots / link to a video to explain it