Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Add active class to main menu

I'm trying to add dynamic active class to my main menu, but i can't able to achieve this,

My jquery is,

<script type="text/javascript">
$(document).ready(function() {
  $('#navi a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});
</script>

My main menu is,

<ul id="navi">
  <li><a href="#">About MHG</a></li>
  <li><a href="#">Workout Programs</a></li>
  <li><a href="#">Fitness Tips</a></li>
  <li><a href="#">Contact Us</a></li>          
  <li><a href="#">Read Our Blog</a></li>
</ul>
like image 734
Vin_fugen Avatar asked Jan 30 '13 15:01

Vin_fugen


2 Answers

Try this

<ul id="navi">
    <li><a class="menu" href="#">About MHG</a></li>
    <li><a class="menu" href="#">Workout Programs</a></li>
    <li><a class="menu" href="#">Fitness Tips</a></li>
    <li><a class="menu" href="#">Contact Us</a></li>          
    <li><a class="menu" href="#">Read Our Blog</a></li>
  </ul>

jquery

$('a.menu').click(function(){
    $('a.menu').removeClass("active");
    $(this).addClass("active");
});

check this Fiddle http://jsfiddle.net/9nd4j/1/

like image 94
krizna Avatar answered Oct 20 '22 17:10

krizna


^^ same as above comment by Rory!!

, if you still need you can do

$("#navi a").live("click", function(){
  $("#navi a").removeClass("active");
  $(this).addClass("active")
});

If you have all the links pointing to a same page above solution works, as i see you going to traverse from one page to another this wont work.

Thanks

like image 1
abhijit Avatar answered Oct 20 '22 16:10

abhijit