Toggle active class in nav bar with JQuery

<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?

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.


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');
});

You'll probably find this better (otherwise the page will jump) -

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

You can do:

$('li').click(function(e){
    e.preventDefault();
   $(this).addClass('active');
    $(this).siblings().each(function(){
        $(this).removeClass('active') ;

    });
});

fiddle here http://jsfiddle.net/UVyKe/1/


Give the ul an id or class, and select off of it.

<ul id = "nav">...

var $navItems = $('#nav > li');
$navItems.click(function(){
    $navItems.removeClass('active');
    $(this).addClass('active');
});

$("ul li").click(function()
{
$("ul .active").removeClass("active");
$(this).addClass("active");
});

You can add active class using below single line without using any event

$('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');

link to refer


Need Your Help

C++ defining a constant member variable inside class constructor

c++ constructor initialization constants

Usually when you have a constant private member variable in your class, which only has a getter but no setter, it would look something like this: