When using jQuery to initialize the active class from navigation, I have encountered an issue. The code only works if there is nothing else after the menu item in the URL.
For example, when I visit the users page like this: site.com/users
, the code functions properly. However, if I navigate to a controller with parameters like this: site.com/users/param1/param2
, the active class disappears.
Below is the code I am currently using:
$(document).ready(function () {
var url = window.location;
// Will only work if string in href matches with location
$('ul.nav a[href="' + url + '"]').parent().addClass('active');
// Will also work for relative and absolute hrefs
$('ul.nav a').filter(function () {
return this.href == url;
}).parent().addClass('active').parent().parent().addClass('active');
});