Find active tab using jQuery and Twitter Bootstrap

I'm a little tired of my brain and I would like to know if anyone knows how I can find the active tab using jQuery and Twitter Bootstrap. Pulling a hash from a URL is not my first option, I use the data-toggle attribute in the <a> link, so there is no need to create a hash URL.

Any insight? Here is 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 am open to any suggestion - using a PHP session, JS cookie, etc.

Edit: This is a real problem. I have a pagination system using PHP, so when the page number or next / previous 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 just send it to the url or session, etc.

+45
jquery twitter-bootstrap tabs
Aug 20 2018-12-18T00:
source share
3 answers

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

 $("ul#sampleTabs li.active") 

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

 var activeTab = null; $('a[data-toggle="tab"]').on('shown', function (e) { activeTab = e.target; }) 
+80
Aug 20 '12 at 15:45
source share

here is the answer for those of you who need a Boostarp 3 solution.

In bootstrap 3, use the 'shown .bs.tab' instead of the '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') ); }); 
+21
Mar 24 '15 at 7:09
source share

First of all, you need to remove the data-toggle attribute. We will use some jQuery, so be sure to enable it.

  <ul class='nav nav-tabs'> <li class='active'><a href='#home'>Home</a></li> <li><a href='#menu1'>Menu 1</a></li> <li><a href='#menu2'>Menu 2</a></li> <li><a href='#menu3'>Menu 3</a></li> </ul> <div class='tab-content'> <div id='home' class='tab-pane fade in active'> <h3>HOME</h3> <div id='menu1' class='tab-pane fade'> <h3>Menu 1</h3> </div> <div id='menu2' class='tab-pane fade'> <h3>Menu 2</h3> </div> <div id='menu3' class='tab-pane fade'> <h3>Menu 3</h3> </div> </div> </div> <script> $(document).ready(function(){ // Handling data-toggle manually $('.nav-tabs a').click(function(){ $(this).tab('show'); }); // The on tab shown event $('.nav-tabs a').on('shown.bs.tab', function (e) { alert('Hello from the other siiiiiide!'); var current_tab = e.target; var previous_tab = e.relatedTarget; }); }); </script> 
+1
May 02 '17 at 11:48 a.m.
source share



All Articles