jQuery
How do I make tabs in jQuery? (Without jQ Tabs plugin)
Last Updated (Wednesday, 22 October 2008 06:59) Written by Alex Grande Tuesday, 02 September 2008 00:39

HTML
<!-- This is to deal with Internet Explorer--> <!--[if lte IE 5]><br /><div><br /><![endif]--> <!--[if IE 6]><br /><div><br /><![endif]--> <!--[if IE 7]><br /><div><br /><![endif]--> <!-- This is the list of tabs. Notice the id begins with the content in the tab. This can be easily replaced with 1, 2, 3 using a simple js loop. Or your backend developer can supply you with a variable to make it scalable. --> <div> <div /> </div> </div> <!--[if IE]><br /></div><br /><![endif]-->
CSS
body {
margin-top:50px;
}
/* Here are the sprites. Only the left part of the image is shown for the selected tab. I love sprites! */
div.tab-selects {
width:111px;
background:url(tab-select-nonselect.gif) no-repeat;
background-position:left center;
float:left;
margin:-40px 10px 0pt;
position:relative;
cursor:pointer;
height:51px;
}
/* Here is a non selected tab. The image on the right! */
div.tab-nonselected {
background-position:right center;
}
div.view-wrapper {
position:relative;
margin-top:74px;
}
/* IE sucks */
.ie div#content {
clear:both;
margin-top:-10px;
}
div#content {
width:610px;
position:relative;
cursor:default;
background-color:#5C81AD;
margin-top:-1px;
border-bottom:1px solid #9D8979;
border-right:1px solid #9D8979;
border-left:1px solid #9D8979;
height:410px;
}
div.view-content {
top:0px;
position:absolute;
width:100%;
overflow-y:auto;
height:410px;
}
div.tab-selects {
text-align:center;
}
div.view-content img {
padding:23px;
}
div.view-nonselected {
visibility:hidden;
}
jQuery Javascript Tabs
//The first tab is going to be opened. We need to know that.
$TabIsOpen = $("#tabSelection div:first");
// The click event
$('.tab-selects').click(
function() {
// So if what you click is not the tab that is already opened then lets change its class
if ($(this) != $TabIsOpen) {
// Look at the CSS to see the properties of this clas
$TabIsOpen.addClass('tab-nonselected');
$(this).removeClass('tab-nonselected');
// Now that this tab is selected we gotta remember it.
$TabIsOpen = $(this);
// jQ can be annoying in creating selectors. But basically we take the id of the tab and it is associated with the content item. We just have to add -content to the end. For instance, #salsa-content.
contentIdChildDiv = "#" + $TabIsOpen.attr("id") + "-content";
// Same deal with the tabs; Hiding and showing.
$("div.view-content").addClass("view-nonselected");
$(contentIdChildDiv).removeClass("view-nonselected");
}
});
// We want to make every instance but the first one hidden for both tabs and content. That's what that crazy div:not(div:first) is all about.
$("#content div:not(div:first)").addClass("view-nonselected");
$("#tabSelection div:not(div:first)").addClass("tab-nonselected");
| Next > |
|---|




doug