Detect and highlight active menu item

By Ken Hawkins

navigation layout menus JS Framework Requires EBI Visual Framework 1.2.0, 1.3.0

Use this pattern to automatically highlight the current menu item depending on path.

Contribute a pattern

Have a great way of doing something, add it to the Style Lab. Here's how


Implementation code

Get a zip with all the sample HTML and any spaecial CSS or JS needed: Download a ZIP file More on how to use this

HTML
<header id="masthead" class="masthead">
  <div class="masthead-inner row">
    <!-- local-title -->
    <div class="columns medium-12" id="local-title">
      <h1><a href="../../" title="Back to [service-name] homepage">Detect active menu item</a></h1>
    </div>
    <!-- /local-title -->
    <!-- local-nav -->
    <nav>
      <ul id="local-nav" class="dropdown menu float-left" data-description="navigational">
        <li><a href="/">Current page (relative)</a></li>
        <li><a href="/some-other-page">Not current page</a></li>
      </ul>
    </nav>
    <!-- /local-nav -->
  </div>
</header>



JS
// Currently this uses jQuery, but could be done without
// Pull Requests welcome! :P
function setNavigation() {
  var path = window.location.pathname;
  console.log('current path:', path)
  path = path.replace(/\/$/, "");
  path = decodeURIComponent(path);

  $("#local-nav a").each(function () {
    var href = $(this).attr('href');
    if (path.substring(0, href.length) === href) {
      $(this).closest('li').addClass('active');
    }
  });
}

$(function () {
  // when jquery is ready...
  setNavigation();
});