Once again, we find ourselves opening up our favorite IDE and looking jQuery straight in the eye. However, instead of a complex script that controls an alien mothership, we are going to build some really simple, yet useful, tabs. Even though jQuery UI offers some pretty cool tab objects, it is still a very large library and sometimes you just need some simple tabs. Today, we are going to tackle this.
Now, when I say simple tabs, I mean something like so:
As you can see they are nothing complicated, and they work. Best of all, the code behind this is literally a few lines of jQuery and a little CSS. Let’s start with our HTML:
<a id="tab-anchor-1" class="tab-anchor selected-tab" href="javascript:ShowTab(1);">
Tab 1
</a>
<a id="tab-anchor-2" class="tab-anchor" href="javascript:ShowTab(2);">Tab 2</a>
<a id="tab-anchor-3" class="tab-anchor" href="javascript:ShowTab(3);">Tab 3</a>
</div>
<div id="tab-1" class="tab">This is tab one!</div>
<div id="tab-2" class="tab">This is tab two!</div>
<div id="tab-3" class="tab">This is tab three!</div>
Alright, so here we have some anchors and some divs, pretty straightforward. However, without styles, nothing looks pretty, so here is what I came up with for styles:
width: 200px;
height: 200px;
display: none;
}
#tab-anchors {
margin-bottom: 4px;
}
.tab-anchor {
background-color: #ccc;
padding: 5px;
border: 1px solid #aaa;
border-bottom: none;
}
.selected-tab {
background-color: #eee;
}
#tab-1 {
background-color: #D480FF;
display: block;
}
#tab-2 {
background-color: #809FFF;
}
#tab-3 {
background-color: #FF7C5C;
}
Again, very simple, nothing too crazy. Now all we need is a few lines of javascript. As you can see in the HTML, we need to define a ShowTab
function, and luckily I have one right here:
{
$(‘#tab-anchors a’).removeClass(‘selected-tab’);
$(‘#tab-anchor-‘ + num).addClass(‘selected-tab’);
$(‘.tab’).hide();
$(‘#tab-‘ + num).show();
}
So there it is. What? Too Easy? Well you better believe it. Basically we have a stack of divs that we show/hide when the anchors are clicked. It really is that simple. Just add some content in the divs and you are ready to go.
Well that wraps it up for this tutorial. Don’t forget to style and fill your tabs, and remember, when you need programming help all you have to do is Switch On The Code.