Reputation: 538
I've put together a very simple tabbed browser which you can see here http://jsfiddle.net/zandergrin/sN2Eu/
I'm just wondering if there was a way to smarten up the script so that all the numbering is handled automatically - ie I can add a new tab and wouldn't need to add new javascript.
I know I can do it with jquery ui, but a) I'm trying to lkeep it super lightweight and, more importantly, b) I'm trying to learn!!
Thanks - I'm pretty basic on my javascript so any explanations would be greatly appreciated
Upvotes: 1
Views: 565
Reputation: 195982
You need to add a comman class to each tab so you can select all of them and a unique id that is also the value in the href
of the links.
Also add a common class to all the links..
<div class="tab-nav">
<ul>
<li><a href="#tab1" class="tabclick active">Overview</a></li>
<li><a href="#tab2" class="tabclick">Specs</a></li>
<li><a href="#tab3" class="tabclick">More Info</a></li>
</ul>
</div>
<div id="tab1" class="tab">
<p>content1</p>
</div>
<div id="tab2" class="tab" style="display: none">
<p>content2</p>
</div>
<div id="tab3" class="tab" style="display: none">
<p>content3</p>
</div>
and your javascript now can be
function tabActions(e) {
// e.preventDefault(); // stop default browser action of link will not add the hash to the url
var targetId = $(this).attr('href'); // extract the value in the href (the #tab1 for example)
$('.tabclick').removeClass('active'); // remove the active class from all links (find them by their common class)
$(this).addClass('active'); // add it to the currently clicked link
$('.tab').hide(); // find all tabs (by the common class) and hide them
$(targetId).show(); // show the current tab
};
$('.tabclick')
.click(tabActions) // bind handler
.filter(function(){ // find the link that points to the hash in the url
return this.hash == window.location.hash;
})
.click(); // manually trigger click on it
Demo at http://jsfiddle.net/gaby/sN2Eu/3/
Upvotes: 2