0

I have this code, where an active menu item has different styling to other menu items:

<div class="menu">
<li class="active"><a href="item1.php">Item 1</a></li>
<li><a href="item2.php">Item 2</a></li>
<li><a href="item3.php">Item 3</a></li>
</div>

Rather than manually code class="active" differently for each page, I'd like to try this with a script that automatically inserts the class to the li tag, based on whether the anchor is the current URL.

Anybody know how I might start this?

alias51
  • 8,178
  • 22
  • 94
  • 166
  • 1
    This is usually done with a serverside script, but you can parse `window.location.pathname` using a regex match if you want – Populus Jul 10 '13 at 16:55
  • when you send the page from the server you set the class name to the current item, or you can set cookies and read them with javascript and set that element with the `active` class – Jorge Y. C. Rodriguez Jul 10 '13 at 16:57

2 Answers2

0

you can get the current url pathname from

window.location.pathname

see this for more details .

Once you know the path name you can set the active class to the correct link like as follows.

$(".menu li a").each(function(){
   if(window.location.pathname == $(this).prop("href")){
        $(.menu li).removeClass("active");     
        $(this).closest("li").addClass("active");
   }
});

Hope that helps

Community
  • 1
  • 1
Kiran Ruth R
  • 902
  • 1
  • 11
  • 28
0

Try this code:

$('.menu li a').each(function(){ //check thru all <a> elements inside <li> inside .menu

  var pagename= location.pathname.split('/').pop(); // get current pages filename (just filename)

    if($(this).prop("href") == pagename){
        $('.menu li').removeClass("active"); // remove all active class    
        $(this).parent("li").addClass("active"); //put active in parent of <a> which is <li>
   }
});
Sergio
  • 28,539
  • 11
  • 85
  • 132