About design and nearby

How to Add Active Navigation Class Based on URL to Menu Item

Posted: February 18th, 2015 | Author: | Filed under: Development, Tips and Tricks | Tags: , , , | No Comments »

When you work on a navigation menu for a website, it would be fine to make it the way the visitors on the website know on which page of the site they are on. This can be accomplished by adding an ‘active’ class to the menu item of the current page.

Active navigation class for menu item

Javascript can access the current URL in parts.

To add an ‘active’ class to the navigation tab of any current page (when page’s url is = link’s href attribute), say, for the code below:

  1. <ul>
  2.  <li><a href="/">Home</a></li>
  3.  <li><a href="/about/">About</a></li>
  4. </ul>

(i.e. to visually indicate it’s the active navigation)
you have to add (after including the jQuery library to your project):

  1. jQuery(function($) {
  2.  var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
  3.  $('ul a').each(function() {
  4.   if (this.href === path) {
  5.    $(this).addClass('active');
  6.   }
  7.  });
  8. });

*The perfect solution is to output this ‘active’ class from the server side, for example, similar solution for MVC:

  1. <div class="btn-group-vertical btn-block" role="group">
  2.         @foreach (var btn in Model.Buttons)
  3.         {
  4.             <button type="button" class="btn btn-default @(((@Request.Url.AbsolutePath.Split('?')[0].Split('/')[Request.Url.AbsolutePath.Split('/').Length – 1]) == btn.Action)? "active" : "")" name="command" value="@btn.Action,@btn.Controller">
  5.                 @btn.Title
  6.             </button>
  7.         }
  8.     </div>

Standalone example: view Active Navigation Class Based on URL in action >>

Share Button

Check Related Posts:


Leave a Reply


  • − 2 = four

Looking for a Freelance UX & UI designer for your project? I’m ready to jump onboard!

Let's discuss your project now