How to Add Active Navigation Class Based on URL

add active class menu For some reason, you may want to use JavaScript to add an active navigation class on the URL especially when you cannot add the class from PHP or ASP. It is a common need to highlight the active class in the menu with a different CSS color or background color.

In this case, you need to use the current or active class to style the class appropriately and display a different color or background color for the active menu item.

Add Active Navigation Class Based on URL

In HTML this is a simple or straightforward process since you just need to attach the current or active class to the a-href or li tags as in the code shared below :

<!-- Primary Navigation -->
<nav id="primary-menu">

	<ul>
		<li><a href="index.html"><div>Home</div></a></li>
		<li><a href="about_us.html"><div>About Us</div></a></li>
		<li class="active"><a href="services.html"><div>Our Services</div></a></li>
		<li><a href="pricing.html"><div>Our Pricing</div></a></li>
		<li><a href="contact_us.html"><div>Contact Us</div></a></li>
	</ul>

</nav>
					
<!-- #primary-menu end -->

You can see the class ‘active in the li tag in the code above.  You can use this class to give a different style to the active element like the color as in the code below :

.active {
    color:#ff000; 
}

jQuery Add Active Navigation Class Based on URL

To implement the same in jQuery you can use the following code :

 /**
  *  Add active menu class based on URL using jQuery 
  *  Copy - https://gist.github.com/Njengah/a68bb0a3e963e636998150fe8fd74881
  */ 
 
 jQuery(function($) {
    
	var path = window.location.href; 
	 
     $('ul a').each(function() {
     
	 if (this.href === path) {
      
	  $(this).addClass('active');
      
	  }
    
	});
});

Similar Articles

 

Comments are closed.