Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class to nav if part of url matchs the menu items

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

like image 894
Learning Avatar asked Dec 11 '25 08:12

Learning


2 Answers

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')
like image 181
kuzma Avatar answered Dec 13 '25 21:12

kuzma


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

like image 40
Deowan Faruque Ahamad Avatar answered Dec 13 '25 20:12

Deowan Faruque Ahamad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!