<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?
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.
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.
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.
$(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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With