3

I am new to jQuery 1.4.3 and Mobile 1.10 and would like to use the tabs widget. I am wondering how to programmatically make a tab active?

Please see the JSFiddle. If I make the 2nd tab as active, the 2nd tab's content does not show until the 2nd tab is clicked.

<div data-role="page">
    <div data-role="tabs">
        <div data-role="navbar">
            <ul>
                <li><a href="#one">one</a>
                </li>
                <li><a href="#two" class="ui-btn-active">two</a>
                </li>
            </ul>
        </div>
        <div class="ui-content" id="one">tab one content</div>
        <div class="ui-content" id="two">tab two content</div>
    </div>
</div>
TylerH
  • 20,799
  • 66
  • 75
  • 101
user1669811
  • 835
  • 3
  • 12
  • 15

5 Answers5

9

Can you not just click the element after adding an ID to the tabs themselves, using something like id="tab-one" and id="tab-two", respectively, then using the following Javascript?

$('#tab-two').trigger('click');

Here it is in a working JSFiddle.

Jeff N
  • 430
  • 3
  • 5
2

jQueryMobile bundles jQuery UI, so from the jQuery UI API docs: http://api.jqueryui.com/tabs/

var tab_index = 1; // the zero based index of tab #two
$("div.tabs").tabs( "option", "active", tab_index ); // tab_index is zero-based
Uilleann
  • 506
  • 4
  • 14
0

I am not a much of JQuery-Mobile guy, but @Jeff's code is all that is needed. I just added some code to make it dynamic: DEMO.

Also you could refer to this QA thread for more info...

$(function(){

// Selectors
var tabs = 'div[data-role="navbar"]';
var tab = tabs + ' a';

// activate the selcted tab on load
activateTab();

// fetch the closest selected tab and trigger click
function activateTab(){
    var selected = $(tab).closest('.ui-btn-active');
    $(selected).trigger("click");
} });
Community
  • 1
  • 1
0

Trying to activate a tab is not so easy when you use multiple pages and trasitions. During trasition the class "ui-btn-active" is removed. So, if you want to select a tab before the page is dispalyed (eg pagebeforeshow), please use this function instead:

function selectTabInNavbar(tabs, nr){
    $( tabs ).tabs( "option", "active", nr );
    $( tabs + " [data-role=navbar] a" ).eq( nr ).addClass("ui-btn-active");
}

where tabs is the selector for the <div data-role="tabs"> container, and nr is the number of desired tab (starting from index 0).

Junior
  • 507
  • 5
  • 19
0

See my full solution here of all the issues I had to fix when using jQuery Mobile tabs!!

SharpC
  • 6,974
  • 4
  • 45
  • 40