close
tony / Optimistic Navigation

Optimistic Navigation

Often if you're building HTML First, you'll have the problem that the interface feels sluggish, because it's not responding immediately to clicks. This can happen in several places but the most common is with a side or top navigation. The user expects that when a link is clicked, the item they clicked on will become active, and the content will begin loading immediately. To do this, we need to do a few things on the frontend.

  • Remove the active class from the current element.
  • Add the active class to the clicked element.
  • Replace the content of the main div with content that indicates it's loading.

Setup

  1. Copy the content of the Code section below into a javascript file.

  2. Trigger the function by passing in the element you'd like to apply the behaviour to. With Mini JS this looks like this:

    <nav :load="applyOptimisticNavigationToChildrenOf(this)">
      <a href="/link-one" class="active">Link One</a>
      <a href="/link-two">Link Two</a>
      <a href="/link-two">Link Three</a>
    </nav>
    

Code

function applyOptimisticNavigationToChildrenOf(element, options={}) {
  const links          = element.querySelectorAll("a");
  const activeClass    = options.activeClass || "active";
  links.forEach(function(linkElement) {
    linkElement.addEventListener("click", function(event) {
      links.forEach(function(linkItem) {
        linkItem.classList.remove(activeClass);
      });
      linkElement.classList.add(activeClass);
    });
  });
}