简体   繁体   中英

Bootstrap navigation bar active state

  • I have a website with a common heading.
  • That heading is included a navigation bar.
  • When I click a navigation item in the bar page load happens.
  • Considering the context how can I set the Bootstrap navigation bar active state for navigation item which is related to the loaded page.

Since there is a page load when clicking on a navigation bar item, I cannot just use

 $(".nav a").on("click", function(){ $(".nav").find(".active").removeClass("active"); $(this).parent().addClass("active"); }); 

Please provide me a better solution.

When the page is loaded you have to check if the links of the anchors match with the page location.

$(".nav a").each(function() {
  if(document.location.href.indexOf(this.href)>=0) {
      $(this).parent().addClass("active");
    }
});

As a solution for my issue, I followed the following way.

I added HTML IDs for each of my navigation bar items. Then in each page related to each navigation bar item, I added Bootstrap active class using javascript as follows.

$("#ID_of_the_navi_bar_item").addClass('active');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM