Make Bootstrap tab Active on the bases of URL link
Asked Answered
L

9

17

I have bootstrap tabs and i want to make tabs active on the bases of URL link.

For example:

xyz.xxx/index#tab2 should make tab2 active on page load.

Here is my code so far

<div class="tab-wrap">
  <div class="parrent pull-left">
    <ul class="nav nav-tabs nav-stacked">
      <li class="active"><a href="#tab1" data-toggle="tab" class="analistic-01">Tab 1</a></li>
      <li class=""><a href="#tab2" data-toggle="tab" class="analistic-02">Tab 2</a></li>
      <li class=""><a href="#tab3" data-toggle="tab" class="analistic-03">Tab 3</a></li>
    </ul>
  </div>
  <div class="tab-content">
    <div class="tab-pane active in" id="tab1">
      <p> hello 1</p>
    </div>

    <div class="tab-pane" id="tab2">
      <p> hello 2</p>
    </div>

    <div class="tab-pane" id="tab3">
      <p>Hello 3</p>
    </div>
  </div> <!--/.tab-content-->
</div><!--/.tab-wrap-->

By default it make tab1 active so there might be possibility in my case to make the second tab active by default on the basis of my URL links.

Suppose if i put #tab2 in URL then it should make tab2 active by default on page load.

Lineman answered 28/12, 2015 at 9:50 Comment(2)
You want to make tabs active on the basis of the URL, like if you pass #tab2 in the url then the tab with id tab2 should be active?Bike
Yep. Something like thisLineman
B
37

You can achieve it using jquery something like this. Your URL for example "www.myurl.com/page#tab1";

var url = window.location.href;

Get the tab to make active from url link.

 var activeTab = url.substring(url.indexOf("#") + 1);

Remove old active tab class

 $(".tab-pane").removeClass("active in");

Add active class to new tab

$("#" + activeTab).addClass("active in");

Or directly open tab after getting activeTab.

$('a[href="#'+ activeTab +'"]').tab('show')
Bike answered 28/12, 2015 at 10:28 Comment(2)
Or just cut out the middleman, and use document.location.hash to get the hash at the end of the visited URLVeedis
What's the agreed best practice for this problem?Rorie
G
18
  1. Get the hash from URL and display active tab
  2. Set the current hash to the URL

You can use this code:

$(function(){
  var hash = window.location.hash;
  hash && $('ul.nav.nav-pills a[href="' + hash + '"]').tab('show'); 
  $('ul.nav.nav-pills a').click(function (e) {
     $(this).tab('show');
     $('body').scrollTop();
     window.location.hash = this.hash;
  });
});
Gyno answered 11/5, 2018 at 10:37 Comment(3)
Works on Bootstrap 4.3.Agitator
Works in Bottstrap 3.3 too. I remove ".nav-pills" in selectors.C
I've tried many methods for this use case with Bootstrap 5 and this one was very helpful, thank you. Most others I tried didn't work with the new version of BS. The only caveat is that BS5 doesn't require jQuery so a pure JS option is probably better overall.Smokeproof
P
2
$(function(){
    var url = window.location.href;
    var activeTab = url.substring(url.indexOf("#") + 1);
    if($.trim(activeTab) == 'Exhibitor') // check hash tag name for prevent error
    {
        $(".tab-pane").removeClass("active in");
        $("#" + activeTab).addClass("active in");
        $('a[href="#'+ activeTab +'"]').tab('show');
    }
});
Prim answered 27/8, 2020 at 14:53 Comment(0)
K
1

Depending on how you have set up your JS you should be able to do this:

www.myurl.com/page#tab1

www.myurl.com/page#tab2

www.myurl.com/page#tab3

Where #tab1, #tab2 and #tab3 are equal to the id of the tab

EDIT

See here: Twitter Bootstrap - Tabs - URL doesn't change

Kufic answered 28/12, 2015 at 10:5 Comment(0)
B
1

You can add an id to <ul class="nav nav-tabs nav-stacked" id="myTab"> then use the following javascript code:

$(document).ready(() => {
  let url = location.href.replace(/\/$/, "");

  if (location.hash) {
    const hash = url.split("#");
    $('#myTab a[href="#'+hash[1]+'"]').tab("show");
    url = location.href.replace(/\/#/, "#");
    history.replaceState(null, null, url);
    setTimeout(() => {
      $(window).scrollTop(0);
    }, 400);
  } 

  $('a[data-toggle="tab"]').on("click", function() {
    let newUrl;
    const hash = $(this).attr("href");
    if(hash == "#home") {
      newUrl = url.split("#")[0];
    } else {`enter code here`
      newUrl = url.split("#")[0] + hash;
    }
    newUrl += "/";
    history.replaceState(null, null, newUrl);
  });
});

For more details follow this link.

Berg answered 22/9, 2018 at 11:30 Comment(0)
M
1

If you just want to trigger it based on url, the you can also do as follow

$(function(){
   var hash = window.location.hash;
   if(hash != ''){
      $("a[href='"+url+"']").click();
   }
})
Maidenhead answered 25/3, 2020 at 10:29 Comment(0)
I
1

This code:

window.addEventListener('load', () => {
  try {
    let url = window.location.href.split('#').pop();
    document.querySelector('#'+url).click();
  } catch {

  }
});

e.g.

http://localhost:5000/#idOfTab

Ieper answered 18/10, 2022 at 11:32 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Crustal
A
0

Using the URL() constructor from the URL API:

URL {
  href: "https://stackoverflow.com/posts/67036862/edit",
  origin: "https://stackoverflow.com",
  protocol: "https:",
  username: "",
  password: "",
  host: "stackoverflow.com",
  hostname: "stackoverflow.com",
  port: "",
  pathname: "/posts/67036862/edit",
  search: ""
}

Make Bootstrap tab Active on the bases of URL link:

$(function() {
  /**
   * Make Bootstrap tab Active on the bases of URL link
   */
  const loc = new URL(window.location.href) || null
  if (loc !== null) {
    console.debug(loc)
    if (loc.hash !== '') {
      $('.tab-pane').removeClass('active in')
      $(loc.hash).addClass('active in')
      $(`a[href="${ loc.hash }"]`).tab('show')
    }
  }
})
Andresandresen answered 10/4, 2021 at 16:43 Comment(0)
A
0

If it can be usefull, I share the solution I'm using with Boostrap 5. It's more complete, cause you can select active tab according to url, OR according to last active tab, stocked on local storage.

  • First : checking if there's active tab on the url. If there's one : active the corresponding tab

  • Second : if no active tab on url, then check local storage to see if there's last visited active tab information, and activate it if it's the case.

      if ($('.tab-content').length) {
    
          //priority 1 : set active tab according to url
          var url = window.location.href;
          var activeTab = url.substring(url.indexOf("#") + 1);
    
          if ( $('[data-bs-target="#'+activeTab+'"]').length) {
              $('[data-bs-target="#'+activeTab+'"]').tab('show');
          }
    
          // priority 2 : keep activ tab according to local storage value
          else {
              $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
                  localStorage.setItem('lastTab', $(this).attr('data-bs-target'));
              });
              var lastTab = localStorage.getItem('lastTab');
              if (lastTab) {
                  $('[data-bs-target="' + lastTab + '"]').tab('show');
              }
          }
      }
    

Here is an example of html code :

<!-- tabs nav links -->
<ul class="nav nav-pills" role="tablist" id="main-tabs">

    <!-- main infos -->
    <li class="nav-item" role="presentation">
        <button type="button" class="nav-link active" role="tab" data-bs-toggle="tab" data-bs-target="#nav-main-infos" aria-controls="nav-main-infos" aria-selected="true">Dossier</button>
    </li>

    <!-- documents -->
    <li class="nav-item" role="presentation">
      <button type="button" class="nav-link" role="tab" data-bs-toggle="tab" data-bs-target="#nav-documents" aria-controls="nav-documents" aria-selected="false">Documents</button>
    </li>
</ul>

<!-- tab contents -->
<div class="tab-content p-2">
    <div class="tab-pane fade show active" id="nav-main-infos" role="tabpanel">
        main infos tab content
    </div>

    <div class="tab-pane fade" id="nav-documents" role="tabpanel">
        document tab content
    </div>
</div>
Alarum answered 2/2, 2024 at 12:34 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.