Add a CSS class on a current active menu item

Author: 

wp beaches


Description: 

With manual menus you may need to add a CSS class to the current menu item that is active, below is a jQuery solution, that utilizes the URL of the page to match the link and add the CSS.

Enqueue the script to where you need it to go.




Kind:

jQuery, PHP


Javascript:

(function($){

$(function() { // Document Ready

activeMenu();

});

// Functions
// @link https://stackoverflow.com/questions/4866284/jquery-add-class-active-on-menu

function activeMenu() {

var url = window.location.pathname,
// create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
// now grab every link from the navigation
$('.menu a').each(function(){
// and test its normalized href against the url pathname regexp
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).addClass('current');
}
});
}

})(jQuery);


URL: