Skip to content
Advertisement

I want to add and remove class when URL having nav tabs id

I have added Bootstrap’s nav-tabs to my project. I was able to add logic that adds current tab’s ID to URL.

Now I would like for my JS to activate tab on page load, based on ID provided by URL parameter/hash.

The problem I am getting now it just picking up the last if condition.

$(document).ready(function() {
  var url = window.location.href;
  if ("url:contains('features#standard-features')") {
    $(".features_tab_nav .feat_nav_item0 a").attr("class", "nav-link cvxcvxc active");
    $(".features_tab_nav .feat_nav_item1 a , .features_tab_nav .feat_nav_item2 a ,  .features_tab_nav .feat_nav_item3 a").removeClass("active");
  }
  if ("url:contains('features#optional-design-features-accesories')") {
    $(".features_tab_nav .feat_nav_item1 a").attr("class", "nav-link cvxcvxc active");
    $(".features_tab_nav .feat_nav_item0 a , .features_tab_nav .feat_nav_item2 a ,  .features_tab_nav .feat_nav_item3 a").removeClass("active");
  }

  if ("url:contains('features#benefits-of-steel-structures')") {
    $(".features_tab_nav .feat_nav_item2 a").attr("class", "nav-link cvxcvxc active");
    $(".features_tab_nav .feat_nav_item0 a , .features_tab_nav .feat_nav_item1 a ,  .features_tab_nav .feat_nav_item3 a").removeClass("active");
  }
  if ("url:contains('features#optional-roof-and-wall-panels')") {
    $(".features_tab_nav .feat_nav_item3 a").attr("class", "nav-link cvxcvxc active");
    $(".features_tab_nav .feat_nav_item0 a , .features_tab_nav .feat_nav_item1 a ,  .features_tab_nav .feat_nav_item2 a").removeClass("active");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Advertisement

Answer

if you declare var url at first then why you using string “url:contains(”)” ??

try this :

if(url.indexOf("features#standard-features") > -1){
// your code
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement