Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Bootstrap tab Active on the bases of URL link

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.

like image 697
Q-bart Avatar asked Dec 28 '15 09:12

Q-bart


2 Answers

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')
like image 97
Anil Panwar Avatar answered Sep 18 '22 13:09

Anil Panwar


  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;
  });
});
like image 44
Patel Disha Avatar answered Sep 18 '22 13:09

Patel Disha