Roal.A Roal.A - 4 months ago 6
HTML Question

removing class and adding class jquery

I am totally new on jquery. When i click to "Invoice" i need to remove the "active and color" class from li and a tag of "Home" . Also the "active and color" classes should be added to the "Invoice" of li and a tag. And so goes for the "Logout"

This is my html code.

<ul class="nav navbar-nav navbar-right" id="navbarprop">
<li id="home" class="active">
<a class="color" href="#"><i class="glyphicon glyphicon-home"></i>&nbsp Home</a>
</li>
<li id="invoice">
<a href="Invoice.aspx"><i class="glyphicon glyphicon-list-alt"></i>&nbsp Invoice</a>
</li>
<li id="logOut">
<a href="#"><i class="glyphicon glyphicon-log-out"></i>&nbsp Log Out </a>
</li>
</ul>


Sorry for my English. Thanks

Answer

var nav = $('#navbarprop');

// Add a click listener to the nav that fires when an anchor within it is clicked.
nav.on('click', 'a', function(event) {
  event.preventDefault();
  // Remove the classes from the current active elements
  nav.find('li.active').removeClass('active');
  nav.find('a.color').removeClass('color');
  // Add the class to current, clicked element(s)
  $(this).addClass('color');
  $(this).parent().addClass('active');
});
li.active {
  font-weight: bold;
}
a.color {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav navbar-nav navbar-right" id="navbarprop">
  <li id="home" class="active">
    <a class="color" href="#"><i class="glyphicon glyphicon-home"></i>&nbsp Home</a>
  </li>
  <li id="invoice">
    <a href="Invoice.aspx"><i class="glyphicon glyphicon-list-alt"></i>&nbsp Invoice</a>
  </li>
  <li id="logOut">
    <a href="#"><i class="glyphicon glyphicon-log-out"></i>&nbsp Log Out </a>
  </li>
</ul>