Pinching the code from the example page by Soh Tanaka that you refer to in your article:
$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
The critical bit is to fix the code to only refer to the current tab group for the purposes of switching between tabs. This is achieved by making sure that where the global context is not desired, only the local group, we change the selector. When referring from a set of tabs to their content, the problem is how to match one with the other, this can either be done with some common ID system, or if tabs are assumed to precede their content, with no overlapping, then we can simply find the next tab_container
along from a tab set.
First, initialisation:
$(".tab_content").hide();
Fine, we want to hide all of them.
$("ul.tabs li:first").addClass("active");
$(".tab_content:first").show();
Not good, this would refer to all tab groups on the page, needs to be specific.
$("ul.tabs").each(function() {
$(this).find('li:first').addClass("active");
$(this).nextAll('.tab_container:first').find('.tab_content:first').show();
});
The .click()
event starts off alright, binding all ul.tabs li
is fine. Inside it needs the selectors changed.
$("ul.tabs li").click(function() {
var cTab = $(this).closest('li');
cTab.siblings('li').removeClass("active");
cTab.addClass("active");
cTab.closest('ul.tabs').nextAll('.tab_container:first').find('.tab_content').hide();
var activeTab = $(this).attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
The last section with the activeTab
is already fine, just be careful not to reuse IDs.
See demo: http://jsfiddle.net/uyvUZ/1/
Visually easier, but different demo: http://jsfiddle.net/uyvUZ/2/