Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Active Tab using jQuery and Twitter Bootstrap

I've been racking my brain for a little while now, and I would like to know if anyone out there knows how I can find the active tab, using jQuery and Twitter's Bootstrap. Pulling the hash from the URL is not my first option, I'm using the data-toggle attribute in the <a> link so there is no need to produce a URL hash.

Any insight? Here's an example of my markup:

<ul class="nav nav-list" id="sampleTabs">     <li><a href="#example" data-toggle="tab">Tab 1</a></li> </ul> <div class="tab-content">     <div class="tab-pane fade active in" id="example">         Example Tab     </div> </div>  <script> $('#sampleTabs a:first').tab('show'); </script> 

I'm open to any suggestion - using a PHP session, JS cookie, etc.

Edit: This is the real issue. I have a pagination system using PHP, so when a page number or next/prev arrow is clicked, it will reload the page. This is why I need to find the active tab before loading the next page, since I"ll just pass it in the url or session, etc.

like image 512
William Orazi Avatar asked Aug 20 '12 15:08

William Orazi


People also ask

How do you check whether the tab is active or not in jquery?

Try this instead: var ref_this = $("ul. tabs li a. active");

How do you make a bootstrap tab active using jquery?

$(document). ready(function(){ activaTab('aaa'); }); function activaTab(tab){ $('. tab-pane a[href="#' + tab + '"]'). tab('show'); };

How do I make the first tab active in jquery?

removeClass('ep_s-click1'). addClass('ep_s1'); }} } }); if i use selected: 0 it will set up the first tab as active but it will now go through the if (theSelectedTab2 == 0) statement and go through adding those classes. if after the page loads i click on those tabs the script works perfect.


2 Answers

Twitter Bootstrap assigns the active class to the li element that represents the active tab:

$("ul#sampleTabs li.active") 

An alternative is to bind the shown event of each tab, and save the active tab:

var activeTab = null; $('a[data-toggle="tab"]').on('shown', function (e) {   activeTab = e.target; }) 
like image 53
João Silva Avatar answered Sep 30 '22 19:09

João Silva


Here is the answer for those of you who need a Boostrap 3 solution.

In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line

// tab $('#rowTab a:first').tab('show');  $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { //show selected tab / active  console.log ( $(e.target).attr('id') ); }); 
like image 38
Daniel Adenew Avatar answered Sep 30 '22 21:09

Daniel Adenew