I'm a jQuery noob and I'm trying to figure out how to trap the tab selected event. Using jQuery 1.2.3 and corresponding jQuery UI tabs (not my choice and I have no control over it). It's a nested tab with the first level div name - tabs. This is how I initialized the tabs
$(function() {
$('#tabs ul').tabs();
});
$(document).ready(function(){
$('#tabs ul').tabs('select', 0);
});
I'm not able to figure out how to trap any of the events or properties (selected tab, when tab clicked, etc). Would appreciate any help on this...
I tried things like:
$('#tabs ul').bind('tabsselect', function(event, ui) {
selectedTab = ui.index;
alert('selectedTab : ' + selectedTab);
});
(OR)
$('#tabs').bind('tabsselect', function(event, ui) {
with no success.
Below is the markup
<div id="tabs">
<UL>
<LI><A href="#fragment-1"><SPAN>Tab1</SPAN></A></LI>
<LI><A href="#fragment-2"><SPAN>Tab2</SPAN></A></LI>
<LI><A href="#fragment-3"><SPAN>Tab3</SPAN></A></LI>
<LI><A href="#fragment-4"><SPAN>Tab4</SPAN></A></LI>
</UL>
<DIV id=fragment-1>
<UL>
<LI><A href="#fragment-1a"><SPAN>Sub-Tab1</SPAN></A></LI>
<LI><A href="#fragment-1b"><SPAN>Sub-Tab2</SPAN></A></LI>
<LI><A href="#fragment-1c"><SPAN>Sub-Tab3</SPAN></A></LI>
</UL>
</DIV>
.
.
.
</DIV>
The correct method for capturing tab selection event is to set a function as the value for the select
option when initializing the tabs (you can also set them dynamically afterwards), like so:
$('#tabs, #fragment-1').tabs({
select: function(event, ui){
// Do stuff here
}
});
You can see the actual code in action here: http://jsfiddle.net/mZLDk/
Edit: With the link you gave me, I've created a test environment for jQuery 1.2.3 with jQuery UI 1.5 (I think?). Some things obviously changed from then. There wasn't a separate ui
object which was separated from the original event
object. The code looks something like this:
// Tab initialization
$('#container ul').tabs({
select: function(event) {
// You need Firebug or the developer tools on your browser open to see these
console.log(event);
// This will get you the index of the tab you selected
console.log(event.options.selected);
// And this will get you it's name
console.log(event.tab.text);
}
});
Phew. If there's anything to learn here, it's that supporting legacy code is hard. See the jsfiddle for more: http://jsfiddle.net/qCfnL/1/
Edit: For those who is using newer version of jQuery, try the following:
$("#tabs").tabs({
activate: function (event, ui) {
console.log(event);
}
});