Halloween Sale 15% off Ends in See the plans
HTML

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.