Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle active class in nav bar with JQuery

Tags:

html

jquery

css

<ul>
                <li id="tabHome" class="active"><a href="@Href("~")">Home</a></li>
                <li id="tabCMDS"  ><a href="@Href("~/CMDS")">CMDS</a></li>
                <li id="tabServiceMonitor" ><a href="@Href("~/Monitor")">Service Monitor</a></li>
                <li id="tabBatchInterface" ><a href="@Href("~/BatchInterface")">Batch Interface</a></li>
            </ul>

So I wanted to bind to click of each of these Id's, and set class="active" on the one that was clicked, and remove it from all others.

I can do the first part, but how can I do the latter?

like image 338
slandau Avatar asked Jun 23 '11 19:06

slandau


People also ask

How do I change the active class on a navbar scroll?

removeClass("active"); to remove all previous active class before adding new class in the below code. If you click on 2nd or greater menu link it makes you scroll to the location but changes active class to previous link.

How do I set active class nav menu?

To set the active class to the navigation menu dynamically by scrolling or clicking on the navigation links, the active class is to be set on each section depending on the position of the webpage. To add methods and variables, JavaScript is used.

What is toggle class in jQuery?

The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.


2 Answers

$(function() {
   $("li").click(function() {
      // remove classes from all
      $("li").removeClass("active");
      // add class to the one we clicked
      $(this).addClass("active");
   });
});

It would be wise to give meaningful classes to the <li>'s so you can properly select just those, but you get the idea.

like image 135
Björn Avatar answered Oct 08 '22 18:10

Björn


No need to bind a click event to each ID but instead bind to all of the list items of this unordered list. Then use the .parent().children() methods. Following should work:

$('ul li').click(function(){
  $(this).addClass('active');
  $(this).parent().children('li').not(this).removeClass('active');
});
like image 11
Marlin Avatar answered Oct 08 '22 20:10

Marlin