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.
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Arun Kumar
Arun is a creative UI Developer