Jquery – Add Tabs without a Plugin

jQuery tabs are often covered but also often used, and like the scrolling trick above it’s important to know how to do these without a plugin.

The first thing to do is write our markup, which should be perfectly presentable in the absence of Javascript:

<div>
<h3>Popular</h3>
<ul>
<li>Item #1</li>
<li>Item #2</li>
<li>Item #3</li>
</ul>
</div>
<div>
<h3>Recent</h3>
<ul>
<li>Item #1</li>
<li>Item #2</li>
<li>Item #3</li>
</ul>
</div>


With a bit of styling, this would look just fine, so we know our jQuery is going to degrade gracefully. Now we can write the code:

$(document).ready(function() {
$("div.widget").hide().filter(":first").before("<ul class='tabs'></ul><div class='tab-content'></div>").add("div.widget").each(function(){
$(this).find("ul").appendTo(".tab-content");
$("ul.tabs").append("<li>" +$(this).find(":header:first").text()+ "</li>");
});
$("ul.tabs li").click(function(){
$(this).addClass("active");
$(".tab-content ul").slideUp().eq($("ul.tabs li").index(this)).slideDown();
});
$("ul.tabs li:first").click();
});

Of course, that’s just one way to do it. 😉

 

 

One Reply to “Jquery – Add Tabs without a Plugin”

Leave a Reply

Your email address will not be published. Required fields are marked *

*