Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap tab activation with JQuery

I have the following code:

<ul class="nav nav-tabs">     <li><a href="#aaa" data-toggle="tab">AAA</a></li>     <li><a href="#bbb" data-toggle="tab">BBB</a></li>     <li><a href="#ccc" data-toggle="tab">CCC</a></li> </ul> <div class="tab-content" id="tabs">     <div class="tab-pane" id="aaa">...Content...</div>     <div class="tab-pane" id="bbb">...Content...</div>     <div class="tab-pane" id="ccc">...Content...</div> </div> 

And the following script:

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

In this case when the page is ready, the second tab will be activated but I always get a JavaScript error in the line $('.tab-pane a[href="#' + tab + '"]').tab();

Can anyone help me, please?

like image 575
user2607411 Avatar asked Jul 24 '13 09:07

user2607411


People also ask

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.

How do you activate a tab?

To change between tabs, click the tab you want to become active. You can also use any of the below shortcut keys when working with tabs in most programs. Ctrl + Tab = Switch between open tabs. Ctrl + Shift + Tab = Switch between open tabs in opposite direction.


2 Answers

Applying a selector from the .nav-tabs seems to be working: See this demo.

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

I would prefer @codedme's answer, since if you know which tab you want prior to page load, you should probably change the page html and not use JS for this particular task.

I tweaked the demo for his answer, as well.

(If this is not working for you, please specify your setting - browser, environment, etc.)

like image 162
MasterAM Avatar answered Sep 22 '22 10:09

MasterAM


Perform a click on the link to the tab anchor whenever the page is ready i.e.

$('a[href="' + window.location.hash + '"]').trigger('click'); 

Or in vanilla JavaScript

document.querySelector('a[href="' + window.location.hash + '"]').click(); 
like image 29
Kamran Ahmed Avatar answered Sep 24 '22 10:09

Kamran Ahmed