Let us say i have following main menu structure for which i need to add class active class to nav if part of url matches the menu link
for example
www.domain.com/en/blog/this-is-firt-blog in this case i need to add active class to second item in name /blog
<div class="wrapper">
<ul>
<li><a href="/en/">Home</a></li>
<li><a href="/en/blogs/" >All Blogs</a></li>
<li><a href="/en/videos/" >All Videos</a></li>
<li><a href="/en/contact/" >Contact Us</a></li>
</ul>
</div>
https://codepen.io/anon/pen/aYBzRd
I use below code to match the part of url which is /blog but this code adds active class to all menu items
$(".wrapper li a").first().removeClass("active-menu");
var pathnameurl = window.location.pathname;
if (pathnameurl.indexOf('/blog') != -1) {
// alert("match");
$(".wrapper li a").each(function (index, element) {
$(element).addClass("active");
});
}
else
{
alert("nomatch");
}
I tried using $(this).addClass("active"); but that also adds active class to all menu items
Why don't you try something like this:
$('[href*=blog]').addClass('active')
https://codepen.io/kuzmanovic/pen/pLNJNo?editors=1111
p.s. your css also required change to work
EDIT: If you need to add slash to css selector:
$('[href*="/blog"]').addClass('active')
Use This
$(".wrapper li a").removeClass("active");
var pathnameurl = window.location.pathname; //'someurl/en/blogs/'
$(".wrapper li a").each(function (index, element) {
var $el = $(this);
var href = $el.attr('href');
if (pathnameurl.indexOf(href) >= 0)
$el.addClass("active");
});
https://codepen.io/anon/pen/eMBNMB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With