Highlight Current Menu Button

Highlight the menu button for the currently viewed web page, with this small JavaScript function. Click around the demo menu below to see the highlighted menu button change depending on what page is being viewed.

Works in all browsers and IE8+

Please view the source of this page for HTML markup, CSS and JS.

How it Works

The script works by comparing the page's filename from the URL, to any href values in the menu, and if they match, it adds a class to the anchor's parent <li>.

Additionally, it adds the page name as a class to the <body> tag.

So, using the example above, if you were viewing the "about-us.htm" page in a web browser, the menu <li> for "About Us" gets a ".current" class, and the <body> element get a ".about-us" class;

<body class="about-us">
<nav class="demo-nav">
  <ul>
    <li><a href="index.htm">Home</a></li>
    <li><a href="abount-us.htm" class="current">About</a></li>
    <li><a href="our-services.htm">Services</a></li>
    <li><a href="contact-us.htm">Contact</a></li>
  </ul>
</nav>

Note that the navHighlight() JavaScript function takes 3 parameters;

  1. The CSS selector to the a elements in the menu
  2. The file name of the home page
  3. The class you want to give current / active menu items

Pop it above the closing </body> tag.

More demos and snippets

Did you find this useful? There are more demos and code snippets this way.