Bill
Bill

Reputation: 1477

How to select the first visible jquery tab

I have a jQuery tab set up and I currently have the ability to hide tabs using

$("[href='"+ tabRef +"']").closest("li").hide();

I then put the tabRef into an array and pull it out if I need to display that tab again

$("[href='"+ tabRef +"']").closest("li").show();

What I need to do is to set the first visible tab active. If I use

$("#tabs").tabs("option", "active", 0);

It will set the first tab active even if it is not visible. What do I need to do to set the first tab visible? Loop the tabs and check the properties? or is there something I can add to the active code that will not make hidden tabs active?

Upvotes: 3

Views: 2712

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Working fiddle.

You could select the index of the first visible tab using :

var first_visible_tab_index = $( "li" ).index($("li:visible:eq(0)"));

Then active the tab using the returned inde :

$("#tabs").tabs("option", "active",  first_visible_tab_index );

Hope this helps.

$("#tabs").tabs();

$("#tabs").tabs("option", "active", $( "li" ).index( $("li:visible:eq(0)") ));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/base/jquery-ui.css" rel="stylesheet"/>

<div id="tabs">
  <ul>
    <li style='display:none'><a href="#tabs-0">Tab 0</a>
    </li>
    <li><a href="#tabs-1">Tab 1</a>
    </li>
    <li><a href="#tabs-2">Tab 2</a>
    </li>
    <li><a href="#tabs-3">Tab 3</a>
    </li>
  </ul>
  <div id="tabs-0" style='display:none'>
    <p>Content for Tab 0</p>
  </div>
  <div id="tabs-1">
    <p>Content for Tab 1</p>
  </div>
  <div id="tabs-2">
    <p>Content for Tab 2</p>
  </div>
  <div id="tabs-3">
    <p>Content for Tab 3</p>
  </div>
</div>
<div id="tabid"></div>

Upvotes: 3

Related Questions