Perfect tabs using jQuery (no plugin)


Using tabs on a website is a common practice these days. Still, most of us make use of jquery plugins to activate them. While there is no issue with that, but how about using tabs with less than 10 lines of jquery code? Hard to believe? Let’s see how we can do that.


Before we go further with this, here are the two most important links. Demo or Download.


Let’s have a look at the jquery code which we will be using to activate tabs on a webpage.

$(document).ready(function() {

	$(".inner-tabs li").click(function() {
		var activeTab = $(this).find("a").attr("href");
		$(".inner-tabs li").removeClass("active");

Here is the HTML.

<ul class="inner-tabs">
			<li class="active"><a href="#tab1">Tab One</a></li>
			<li><a href="#tab2">Tab Two</a></li>
			<li><a href="#tab3">Tab Three</a></li>

		<div id="tab1" class="tab">
			<p>The content for <strong>Tab 1</strong> goes over here.</p>

		<div id="tab2" class="tab">
			<p>The content for <strong>Tab 2</strong> goes over here.</p>

		<div id="tab3" class="tab">
			<p>The content for <strong>Tab 3</strong> goes over here.</p>

As you can figure out the ul class is “inner-tabs” and each div holding the tab content is having the “tab” class. Now, let’s find out what’s going through the jquery code.

The first two lines of the code after document ready() function makes all the tab content holding div hide and just displays the first div. This will be the initial state of the tabs. The first tab and its content will be visible by default. Then after this we have the .click() function. Here, we are performing the following steps:

  1. Detect if any of the tab boxes are clicked
  2. Find the href of the ul >li > a element
  3. Remove “active” class from all the li elements
  4. Add “active” class to the current clicked element
  5. Hide all the divs with the class “tab”
  6. And finally, show the div with the same ID as present in the href element we got in step 2


I am sure you must be expecting a couple of steps more but to your dissapointment there are no more steps to follow. You have your tabs ready with you. Just sprinkle a bit of CSS as per your choice or use the one that comes with the demo.[/sociallocker]

I love hearing from you guys. Let me know if you found this useful.


Leave a Comment.