Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Find active tab

Tags:

jquery

I have a list of tabs:

<ul class="tabs">
<li><a data-id="1" href="#">AAA</a></li>
<li><a data-id="2" href="#" class="active">BBB</a></li>
<li><a data-id="3" href="#">CCC</a></li>
</ul>

Then I have a button:

<div id="button">Click Me</div>

How can I, when click on the button, access the element that have the class active? I need to be able to get the data-id from the active item.

So, something like this... (this doesn't work!)

$("#button").live("click", function(){

        var ref_this = $("ul.tabs li a").find(".active");
        alert(ref_this.data("id"));

});
like image 944
TiagoSouEu Avatar asked Sep 25 '13 21:09

TiagoSouEu


People also ask

How do I know which tab is clicked in jQuery?

var selectedTab = $("#TabList"). tabs(). data("selected. tabs");

How do you check if a browser tab is currently active or not?

The Page Visibility API: It lets the developers know if the current tab is currently active or not. When the user switches to another tab or minimizes the window, then the pagevisibilitychange event gets triggered. This API added these properties to the document object. document.

How do you active a tab?

With Tab Activate, new tabs open immediately instead of in the background. To override Tab Activate and open a new tab in the background, press the Shift key while opening the new tab. Note: Override does not work for bookmarks. Tab Activate effectively reverses Chrome's new tab focus behavior.


2 Answers

You already selected the a, and find() searches descendants. Try this instead:

var ref_this = $("ul.tabs li a.active");

Side note: live() is deprecated as of version 1.7. on() is the new hotness.

like image 175
Jason P Avatar answered Sep 20 '22 16:09

Jason P


$(document).ready(function () {
       $("#tabs").on("click", function (e) {
        //debugger
        //var ref_this = $("ul.tabs li a.active");

        var target = $(e.target).attr("data-id");
        if (target != null)
             alert(target);
        else
             alert('There is no active element');

       });
});

Here is my TAB list

<ul class="nav nav-tabs" id="gtu-tab">
        <li class="active"><a data-id="1" href="#Boys" id="boys-tab" data-toggle="tab">Boys</a></li>
       <li><a data-id="2" href="#Girls" id="girls-tab" data-toggle="tab">Girls</a></li>
</ul>
<div id="tabs" class="tab-content">
       <div class="tab-pane active" id="Boys">
             <p>Hey....</p>
             <p>Boys are here</p>
       </div>
       <div class="tab-pane" id="Girls">
             <p>Hey....</p>
             <p>Girls are here</p>
       </div>
</div>

and button over here

<input id="Div1" type="button" value="Click Me"/>
like image 26
Utpal Patel Avatar answered Sep 21 '22 16:09

Utpal Patel