user3839473 user3839473 - 6 months ago 25
jQuery Question

change font color when clicking on menu with jquery

I want to change item color and it's parent when click on menu and sub menu .
like this menu . but when I click on sub menu ,color of parent menu is removed.

<div id="navbar-collapse-grid" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown yamm-fw">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">main menu<b class="caret"></b></a>
<ul class=" navbar-nav dropdown-menu">
<!-- Grid 12 Menu -->
<li class="dropdown yamm-fw">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">menu1<b class="caret"></b></a> <ul id="menu1" class="dropdown-menu">
<li class="grid-demo">
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>

<script>

$('li a').click(function () {

$(' li a').removeClass('active');
{
$(this).parent('a').addClass('active');
$(this).addClass('active');

}

});

</script>

.active{
color:#DC0000 !important;
}

Answer
$('li a').click(function () {
  // reset all 
  $('ul.nav a').removeClass('active');

  $(this).addClass('active');

  $(this).parents('li').find('a').filter(function () {
    return !$(this).closest('ul').hasClass('dropdown-menu');
  }).addClass('active');

  // or
  // $(this).parents('li').find('a.dropdown-toggle').filter(function () {
  //    return !$(this).closest('ul').hasClass('dropdown-menu');
  // }).addClass('active');  
});

Example-1

Example-2