Highlight the Menu Link of the Section in View
Marks the menu link that points to the section currently on screen (for one-page sites with #about, #services links), updating as visitors scroll.
Opens WPIDE on
Code
<style>
a.is-current{font-weight:700;text-decoration:underline;text-underline-offset:.3em;}
</style>
<script>
(function () {
if (!('IntersectionObserver' in window)) { return; }
var links = Array.prototype.filter.call(document.querySelectorAll('nav a[href*="#"]'), function (a) {
return a.hash.length > 1 && a.pathname === window.location.pathname && document.getElementById(decodeURIComponent(a.hash.slice(1)));
});
if (!links.length) { return; }
var byId = {};
links.forEach(function (a) { var id = decodeURIComponent(a.hash.slice(1)); (byId[id] = byId[id] || []).push(a); });
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (!entry.isIntersecting) { return; }
links.forEach(function (a) { a.classList.remove('is-current'); a.removeAttribute('aria-current'); });
(byId[entry.target.id] || []).forEach(function (a) { a.classList.add('is-current'); a.setAttribute('aria-current', 'location'); });
});
}, { rootMargin: '-45% 0px -50% 0px' });
Object.keys(byId).forEach(function (id) { io.observe(document.getElementById(id)); });
})();
</script>
Notes
Give each section an HTML anchor (Advanced > HTML anchor) matching the menu links. The active link gets the class is-current and aria-current.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.