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
slandau
source share7 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
Björn
source shareYou 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
Marlin
source shareYou 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
Phil carr
source shareYou 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
Nicola Peluchetti
source shareGive ul id or class and select it.
<ul id = "nav">... var $navItems = $('#nav > li'); $navItems.click(function(){ $navItems.removeClass('active'); $(this).addClass('active'); }); 0
Stefan kendall
source share $("ul li").click(function() { $("ul .active").removeClass("active"); $(this).addClass("active"); }); 0
Itai sagi
source shareYou can add an active class using a single line without using any event
$('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active'); -one
Manthan vaghani
source share