Udara Seneviratne
Udara Seneviratne

Reputation: 2483

Bootstrap navigation bar active state

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.

Upvotes: 0

Views: 52

Answers (2)

Vladu Ionut
Vladu Ionut

Reputation: 8183

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");
    }
});

Upvotes: 1

Udara Seneviratne
Udara Seneviratne

Reputation: 2483

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');

Upvotes: 0

Related Questions