Ad goes here

Saturday, 24 January 2015

How to active/ highlight menu based on current URL?

jQuery As I have mentioned in my previous article that jQuery will give you a quick solution by using a single line code and today we will discuss about how it works when you creating a web application. We all know navigation/ menu is the most important part of a web application which works as a guide for users that where they are currently. Most of them we know the technique is normally done by adding a CSS active class to the menu item to highlight it differently from other menu items. But the issue is when you going to active the current menu, you have to add active class manually for each and every pages, may be its easy for 3 or 4 pages but when the pages are more than 50 or 100? Yes then definitely you will look for the quick solution as a smart designers/ developers.

See, how you can smartly do the things by using few lines of jQury code.


Add following line inside the existing script file or new file.
$(function () {
$(".navigation a").each(function() {  
    if (this.href == window.location.href) {


We are using a class name called 'active' in above code to highlight the area and you can understand that we have to add this class inside a stylesheet.
.navigation li { display:inline; list-style-type:none;}
.navigation li a { padding:5px;}
.navigation li {background:red; color:#fff; padding:5px;} /* this class uses for highlight the active link */


Pleased see the following HTML code where we use a class name called 'navigation' to selecting it from the jQuery.
<ul class="navigation">
<li><a href="">Home</a></li>
<li><a href="">jQuery</a></li>       
<li><a href="">Contact 24 xhtml</a></li>   </ul> </nav>
Assuming most of the readers can understand the benefits of using this, however I will recommend creating 2 – 3 pages html for testing purpose to understand it properly that how it works even after page refresh or in new page access.

Note: Do not forget to add jQuery Library :)

Hope it's helpful for you, please share if you care for others.

No comments:

Post a Comment

Books for you (Crafted with )