Jquery Navigation
Posted in: Jquery

Highlight Current Page Navigation Using Jquery

Jquery NavigationYesterday i was working over my project and after making navigation and put this navigation in a file and using with the help of Include. I came to know that my navigation is not getting highlighted when i open the particular page. I just got same style in all the navigation tabs. Like below image.

jquery Navigation


<div class="navigation-content">
<li><a id="nav" href="parent.html">WEDDING</a></li>
<li><a id="nav" href="vivek.html">CORPORATE</a></li>
<li><a id="nav" href="party.html">PARTY</a></li>
<li><a id="nav" href="#">ABOUT US</a></li>
<li><a id="nav" href="#">CONTACT US</a></li>


<style type="text/css">
.navigation{width: 100%;background-color: #fff;border-bottom: #d8d8d8 solid 2px;float:left}
.navigation-content{width: 980px;margin: auto;padding-top: 10px;}
.navigation-content ul{margin: 0;padding: 0;text-align: left;}
.navigation-content ul li{display: inline-block;list-style-type: none;margin-right: 5px;}
.navigation-content ul li #nav{text-decoration: none;display: block;background-color: #d8d8d8;color: #666;padding: 10px;font-size: 12px;font-weight: bold}
.navigation-content ul li #nav:hover{background-color: #A01C20;color: #fff}

Now when i open Wedding page it is not highlighting if i click on corporate it is the same. Than i figured out that my css is working properly but it is not able to decide that which tab should be highlighted. So i make a Jquery script to make it possible. lets figureout how to Highlight Current Page Navigation Using Jquery or Javascript.

First of all i have to find out that which page is now opened and i got this by using the attr function of jquery.

file = $(location).attr('href');

It get me the whole URL but i need only the page name so that i will use it over my tabs. So i decide to strip the url to the last Slash \. By using the below script.

n = file.lastIndexOf('/');
if (n >= 0) {file = file.substring(n + 1);}

Now i have the page and i have to search for the tabbed active page and add the active css. This is done by just the .css() of Jquery.


In the above line will will search for the whole navigation and add the style to only that tab which is active right now. So the whole code will look like this.

var file, n;
file = $(location).attr('href');n = file.lastIndexOf('/');
if (n >= 0) {file = file.substring(n + 1);}

Thank You. If you have any queries than please comment or if you can modify and make it more better than also comment it will help others too.

~~~~~~Happy Coding~~~~~~  

Leave a Reply

Your email address will not be published. Required fields are marked *