jQuery add class .active on menu

Check this out this WORKS

Html

<div class="menu">

    <ul>
        <li><a href="~/link1/">LINK 1</a>
        <li><a href="www.xyz.com/other/link1">LINK 2</a>
        <li><a href="~/link3/">LINK 3</a>
    </ul>

</div>

Jquery

$(document).ready(function(){
    $(".menu ul li a").each(function(){
        if($(this).attr("href")=="www.xyz.com/other/link1")
            $(this).addClass("active");
    })
})

An easier way for me was:

var activeurl = window.location;
$('a[href="'+activeurl+'"]').parent('li').addClass('active');

because my links go to absolute url, but if your links are relative then you can use:

 window.location**.pathname**

Get the LI elments, loop through, check the HREF:

$('.menu').find('a').each(function() {
    if($(this).attr('href').indexOf('www.xyz.com/other/link1/')>0) {
          $(this).addClass('active');
    }
})

Click here for a solution in jsFiddle

What you need is you need to get window.location.pathname as mentioned and then create regexp from it and test it against navigation hrefs.

$(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
        $('.menu a').each(function(){
            // and test its normalized href against the url pathname regexp
            if(urlRegExp.test(this.href.replace(/\/$/,''))){
                $(this).addClass('active');
            }
        });

});

Tags:

Jquery

Menu