swup

Highlight current link with Swup.js


I use Swup for page transitions and was wondering how I could highlight the currently active link. Imagine I have a page structure like:

<nav>
  <a href="/page-1">Page 1</a>
  <a href="/page-2">Page 2</a>
</nav>
<main id="swup">
  <!-- content -->
</main>

After each nav a click, the page content is being replaced, but I want to have a different style for the currently active link.

Thanks for any help!


Solution

  • You can use the Swup contentReplaced hook to listen for completed page loads, loop through all links that match a specified selector and check if their hrefs are identical to the current url.

    function swupActiveLinks(){
        let currentPath = window.location.pathname;
        let links = document.querySelectorAll('nav a'); // <- put your link selector here
        for (const link of links) {
            let linkPath = (new URL( link.href )).pathname;
            link.ariaCurrent = linkPath == currentPath ? 'page' : false;
        }
    }
    swup.on('contentReplaced', () => {
        swupActiveLinks(); // trigger after swup
    });
    swupActiveLinks(); // trigger on page load
    

    Then style all current links:

    nav a[aria-current=page]{
      text-decoration: underline;
    }