Reputation: 1
I have the following markup to show a navigation menu :
<ul class="nav sf-menu">
<li><a href="@Url.Action("Index","Home")">Home<span></span></a></li>
Now I want to add active
class to the li
if the current URL is equal to its <a>
href.
I have tried the following:
$(function () {
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$"); // 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
// now grab every link from the navigation
$('.sf-menu li').each(function () {
// and test its normalized href against the url pathname regexp
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});
});
but I get an error that li
does not have a href
. How do I get this to work?
Upvotes: 1
Views: 550
Reputation: 15794
The href attribute exists on the <a>
element, not the <li>
element. You need to check the <a>
for the href and then apply the class to the parent <li>
.
Here is how I have tweaked your code to target the <a>
tag:
jQuery(function () {
var url = window.location.pathname;
if (url == '/') {
jQuery('.sf-menu li > a[href="/"]').parent().addClass('active');
} else {
var urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
jQuery('.sf-menu li > a').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
jQuery(this).parent().addClass('active');
}
});
}
});
I've also placed a check for if the link is /
to prevent all the links from being marked as active.
You could also try this simplified version if your links work with it:
jQuery(function () {
var url = window.location.pathname;
jQuery('.sf-menu li > a[href="' + url + '"]').parent().addClass('active');
});
Upvotes: 3