Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add class .active on menu

Tags:

jquery

menu

I've got a problem.

I want to add the class "active" on item menu when the relative page is on.

the menu is very simple:

<div class="menu">  <ul> <li><a href="~/link1/">LINK 1</a> <li><a href="~/link2/">LINK 2</a> <li><a href="~/link3/">LINK 3</a> </ul>  </div> 

In jQuery I need to check if the url is www.xyz.com/other/link1/

if it's this one I would like to add a class one the 'a' element of link1.

I'm trying many solutions but nothing work.

like image 913
Andrea Turri Avatar asked Feb 01 '11 18:02

Andrea Turri


People also ask

How do you add and remove active class on click?

removeClass("active"); $(this). addClass("active"); }); This will remove the active class when clicked then add it to the current item being clicked.

How can make Li active in jQuery?

addClass("active"); // adding active class }); The above code will add the active class to the li tag whenever the user clicks on the Li element.


2 Answers

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');             }         });  }); 
like image 153
Tom Tu Avatar answered Sep 28 '22 01:09

Tom Tu


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** 
like image 23
Pierre Michel Silva Pèrez Avatar answered Sep 28 '22 00:09

Pierre Michel Silva Pèrez