Menu Highlighting with jQuery

Written by Adrian Hart

Topics: Web Design

If you’ve built a menu and you want to style the link which corresponds to the page you are on, you can easily add a class to the link using jQuery and then style it using CSS.

Billy, one of the developers here at Optimise Web, wrote this small, yet effective script to add a class of “active” to all links on the page which link to the current page in the browser…

var url = window.location; // get current URL
$(‘a[href="’+url+’"]’).addClass(‘active’); // add class of ‘active’ to selected links matching current url

In this state any link will get the “active” class added. It would be better to be more specific with the jQuery slector. This would make the javascript more efficient as it is not having to search the entire page for links. So, as an example, I wanted this script to only target links in my menu. So I changed…



[code]$(‘nav ul a[href="’+url+’"]’).addClass(‘active’);[/code]

Say you wanted to highlight the current page’s link in your menu with red text, in your CSS you can add styling to your links like this…

[code]nav ul {color:#900000;}[/code]

And that’s it. Simple!

Leave a Comment Here's Your Chance to Be Heard!