Add active class to site navigation menu with JS

Posted by: Alex on January 18, 2016

A very common feature of sites is a subtle design change to the website menu to indicate the current page the user is on, usually by adding an underline to the menu item of the menu bar.

This can be done in multiple ways, however this JavaScript / jQuery code I have found to be the most performant over the years:

// url, so we can compare the current page the user is on.
var url = window.location.href;
// myMenuLinks, set this to your site's a links inside of some kind of container/loopable structure.
var myMenuLinks = $('#menu a');

myMenuLinks.filter(function() {
    return this.href == url;
}).addClass('active'); // Adds a class of 'active', directly to the 'a' link

There’s also another version if you’re looking to add class of active to menu with PHP