Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap menu change li active class on click

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");
});
like image 351
rikket Avatar asked Mar 19 '14 21:03

rikket


People also ask

How to set active class to Nav menu from Bootstrap?

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.

How do I add an active class to a menu item?

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.

How to add an active class to a li element?

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.

How to make an HTML menu using jQuery and bootstrap CSS?

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.


2 Answers

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

like image 193
Tharaka Avatar answered Sep 29 '22 21:09

Tharaka


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.

like image 36
Deaundrie Howard Avatar answered Sep 29 '22 20:09

Deaundrie Howard