Highlight active navigation link

Posted By : Arun Kumar | 30-Jun-2015

Firstly lets create our HTML  markup :

 

<nav>

    <ul>

        <li><a href="/">Page1</a></li>

        <li><a href="/page2/">Page2</a></li>

        <li><a href="/page3/">Page3</a></li>

        <li><a href="/page4/">Page4</a></li>

    </ul>

</nav>  

 

and CSS for styling the active link ,

 

nav li.active{


  background:blue;

 color:white;

}

 

 

To highlight the anchor( from the list item) ,we are going to simply add class "active" to it and its background will be blue and the text will turn white.

 

Now to add the "active" class to the specific navigation item we will write this jquery code.

 

$(document).ready(function(){

 

    $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');

});

 

 

The method location.pathname.split() reads the url and matches it with the href attribute of the anchor inside the list item.

and the addClass method is also chained to add class "active" to it and that's it.

 

About Author

Author Image
Arun Kumar

Arun is a creative UI Developer

Request for Proposal

Name is required

Comment is required

Sending message..