Home
  • Switch active class to navigation bar using 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> 

    Therefore, I wanted to associate with the click each of these identifiers and set class="active" to the one that was clicked, and remove it from all the others.

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

    +7
    source share
    7 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 <li> classes so that you can choose the right ones, but you understand the idea.

    +22
    source

    You do not need to bind the click event to each identifier, but instead bind to all list items this unordered list. Then use the .parent () methods. Children (). The following should work:

     $('ul li').click(function(){ $(this).addClass('active'); $(this).parent().children('li').not(this).removeClass('active'); }); 
    +6
    source

    You will probably find it 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; }); }); 
    +2
    source

    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/

    +1
    source

    Give ul id or class and select it.

     <ul id = "nav">... var $navItems = $('#nav > li'); $navItems.click(function(){ $navItems.removeClass('active'); $(this).addClass('active'); }); 
    0
    source
     $("ul li").click(function() { $("ul .active").removeClass("active"); $(this).addClass("active"); }); 
    0
    source

    You can add an active class using a single line without using any event

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

    link for link

    -one
    source

    All Articles