Search code examples
jquerybootstrap-4

Class active on nav-pills using jQuery


I have a site I'm working on where I'm using a nav-pills setup with bootstrap 4. I want to add an active state on click for the two links I have that use accordions to drop the content into view. I have the following jQuery I'm using:

$(function () {
$("#filtermenu li a").click(function () {
    $("#filtermenu li a.active").removeClass("active");
    $(this).addClass("active");
});
});

This works fine on click and switches depending on which tab you click on but it always stays active on one of the links meaning you can't get rid of the active class.


Solution

  • you are always adding 'active' class and you always get an active element, if I understand you correctly, you want to close the drop down by clicking on the already 'active' element. so

    $(function () {
      $("#filtermenu li a").click(function () {
        if($(this).hasClass('active')) {
          $(this).removeClass("active");
        } else {
          $("#filtermenu li a.active").removeClass("active");
          $(this).addClass("active");
        }
      });
    });