I have the following menu by bootstrap
HTML
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active" id="homeL"><a data-scroll href="#Home">Home</a></li>
<li><a href="#">About</a></li>
<li class="" id="workL"><a data-scroll href="#Work">Work</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
how can I alter changing the <li>
class to active when either home or work is clicked?
The following isn't working for me
$("#homeL").on("click",function(){
$(".nav navbar-nav li").removeClass("active");
$(this).addClass("active");
});
How to set active class to nav menu from bootstrap ? 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.
To add it, we need to add some jQuery to our project, that will check the page URL that the user or visitor is viewing, and compares with the one on the menu item. If they mach, it’ll add the .active class to that menu item. If you don’t have the jQuery library added to your project yet, this won’t work.
Or, if u want to do it by plain javascript, you can do that too. Here’s how. First you got to add a #nav ID to your <nav> element. Then, use this code to add the active class to the li a element.
1. Load the jQuery and Bootstrap CSS in the head tag of your HTML page. Basically, Bootstrap CSS is optional, the menu works well without it. Anyhow, the menu uses the Bootstrap color classes. 2. After that, create the HTML nav element and arrange navigation links in unordered list. Use the nested list to make the submenus that will open on click.
UPDATED
Your css selectors seems to be wrong. Please try as given below,
<script>
$(".nav li").on("click", function() {
$(".nav li").removeClass("active");
$(this).addClass("active");
});
</script>
I have created a plunkr for this here
Try this:
$("ul li").on("click", function() {
$("li").removeClass("active");
$(this).addClass("active");
});
You will have to play around with it with your given tags. What helped me was declaring this to become active, then removing the active class.
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