Make a terrific tab switcher in jQuery

August 23rd, 2009 in Javascript, Tutorials
preview

jQuery is a very flexible javascript library, allowing you to fulfill any needs you have (in javascript). In this tutorial we’ll be making a nice tabbed interface, all for your amusement and use. Hopefully you’ll learn something new or something like that.

This is cool, will you be writing more on jQuery?

Of course! If you want to suggest a tutorial, either post it in the contact area or contact me via the contact form. Don’t worry, we won’t bite. I’ll try my best to try and get the tutorial wrote for you, or you could even submit yourself to write for us!

Anyway, hit the break to read the tutorial.





Let’s get started then

I’m not really going to explain the HTML and CSS in this tutorial, as I’ve done tutorials on this before, but if you’re not very good at CSS and XHTML you can check out this tutorial on how to make an XHTML and CSS layout if you don’t know any HTML or CSS.

So as always, include the javascript files in the head section of your document, as you would do normally. Below I’ve included the regular jQuery.js file, and also an external file where our custom code will be going (script.js).

<script src="jquery.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>

Once you have that done, lets add a sprinkle of HTML.

<a href="#home">
	<span class="tab home">
		Home
	</span>
</a>

<div class="content home">
Quisque lacus sapien, pellentesque pellentesque dapibus non, tempor sed lacus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse arcu nunc, pretium a ultricies et, tempus blandit mauris.
</div>

So what we have here is a span element enclosed in an anchor, so the whole tab will become clickable. The span has two classes, tab and home. Tab is going to be necessary to define this as one of the tabs. Home, is the defining part of this tab. The div has two classes too, content and home. The content class defines this as the content that we want to display, and the home is so we can match up the tabs with the content. After this I added 2 more tabs:


<a href="#tutorials">
	<span class="tab tutorials">
		Tutorials
	</span>
</a>
<div class="content tutorials">
Nunc, pretium a ultricies et, tempus blandit mauris. Donec imperdiet volutpat risus non eleifend. Curabitur ut nisl in nisi faucibus gravida et non enim. 

</div>

<a href="#resources">
	<span class="tab resources">
		Resources
	</span>
</a>

<div class="content resources">
 Phasellus posuere malesuada metus a lacinia. Integer ornare, purus ac suscipit posuere, massa quam aliquet velit, eu elementum ipsum risus a tellus.
</div> 

Finally, add an empty div with the id, “holder”:

<div id="holder">

</div>

Next lets add some CSS to the mix:

body {
	font-family: Arial, sans-serif;
}

.content {
	display: none;
}

.tab {
	padding: 27.5px;
	background: #1e2429;
	float: left;
	font-weight: bold;
	position: relative;
	z-index: 1;
	top: 4px;
	border-bottom: 4px solid #2e699d;
}

.active {
	background: #3f81ba;
	border: 4px solid #2e699d;
	border-bottom: 0px;
}

#holder {
	clear: left;
	font-size: 14px;
	padding: 30px;
	background: #3f81ba;
	display: none;
	color: #bdd8ef;
	width: 300px;
	border: 4px solid #2e699d;
	line-height: 25px;
	text-align: justify;
}

a {
	text-decoration: none;
}

a > .active {
	color: #275a88;
}
a:hover > .active {
	color: #1e4b73;
}

a {
	color: #626f7a;
}
a:hover {
	color: #2c3339;
}

This is pretty straight forward. The > just means that the children of this element will have these attributes. Oh yeah, and z-index is a bit of a rare attribute. It’s just the order of the elements. A higher number translates to ontop of more elements. Since we only have one with z-index, 1 will suffice. Clear: left; just means that float: left; will not apply to the holder, meaning it will be below the tabs. Anyway, lets get stuck right into the jQuery.

jQuery, God amongst Javascript Libraries

Go ahead and open up your script.js file in notepad. As always in a jQuery document, we start like this:

$(document).ready(function() {

}

All the javascript will go inbetween these brackets. We’ll start off by defining the click function for the tab classes:


	$('.tab').click(function() {

        });

First off, we’re selecting the tab class by saying $('.tab'). The dot tells jQuery that this is a class. Then we initiate the click() function, and attach a function to it. This allows us to continue modifying what will happen when the person clicks on a tab.

Next we’re going to define two variables:

		var classy = $(this).attr("class").split(" ").splice[1];
		var innerhtml = $('.content.'+classy).html();

Lets break this down. First we define the variable name by writing var classy. Then we select the currently clicked item, and get the attribute, “class” from it. Since there are more than two classes, and we only want to find out the class that defines this tab. So we split the classees into two parts by the same, and splice out the bit we want to keep, by saying 1, so that it only selects the last class.

The next variable finds gets the content class, plus the currently selected class, so if you clicked the home tab, we’ll be selecting ‘.content.home’. the html() function gets the html inside this div, thus why the variable is called innerhtml.

Next:

if($(this).is(".active")) {
	return;
}

This code makes sure that the click for the currently selected tab is disabled, or returns nothing. Why? Since without this, double clicking on the a tab causes the content to disappear. So you’re probably wondering, “Yeah, but how do I change a tab to active or not?” We’ll get to that in a minute. First, lets get the information to slide down.

	$('#holder').html(innerhtml).slideDown("slow");

This will mean the information will slide down the first time the user comes to the page. This is just a nice little effect, you could just make it show() if you really wanted to.

Finally, to create the illusion that the tabs are switching, we use this code:

		$('.tab').removeClass('active');
		$(this).addClass('active');

This removes the “active” class from all the tab elements in your html. This means we don’t end up with all the tabs being highlighted eventually. The next line selects this element and adds the active class, causing it to be highlighted.

Usability

You’ll notice that in the html we have the urls set to things like #home, #tutorials, etc. Now these are pretty useless at the moment: They won’t do anything. We’re going to make it so if the user is at #tutorials, the tutorial tab will be highlighted, or if they haven’t got anything selected (no hash) the first tab will be selected. So how do we do this? Well, let me show you. First we have to get the url, and convert it to a string. This isn’t as hard as it sounds, and it just amounts to this line:

	var url = document.location.toString();

That’s pretty straight forward, right? Document.location is the url, and we convert it to a string with toString();.

Next we check if there are any hashes followed by letters, such as would appear if the user was targetting a page.


	if(url.match(/#([a-z])/)) {

        }

match checks the url for the bit in the brackets. Don’t know what the bit in the brackets are? That’s called regular expression. the ([a-z]) bit searches for any lowercase letter. The two forward slashes are the start and end of the regular expression (regex). The hash is what we want it to start with.

Here is the overall code for this section:

	if(url.match(/#([a-z])/)) {

		var split = url.split("#").splice[1];
		$('.tab.'+split).click();

	}
	else {
		$('.tab:first').click();
	}

The var split is similar to what we did before in the click function. We’re seperating the url by a # sign and getting the last element. Then we’re selecting the .tab.[split] element. So if you were at #home, we would be selecting .tab.home. Then we click this. This initiates the click function, and voila, the tab becomes selected.

Otherwise (else {), the first .tab element will be selected, and clicked.

Final jQuery Code
$(document).ready(function() {

    $('.tab').click(function() {
        if ($(this).hasClass("active")) {
            return;
        }

        var classy = $(this).attr("class").split(" ")[1];
        var innerhtml = $('.content.' + classy).text();

        $('#holder').html(innerhtml).slideDown("slow");

        $('.tab').removeClass('active');
        $(this).addClass('active');
    });

    var url = document.location.toString();

    if (url.match(/#([a-z])/)) {
        //There is a hash, followed by letters in it, therefore the user is targetting a page.
        var split = url.split("#")[1];
        $('.tab.' + split).click();
    }
    else {
        $('.tab:first').click();
    }
});

Hope you’ve enjoyed this tutorial. We’ll have more in the future so don’t forget to subscribe and follow us on twitter!


Share This

 

 
 

Author: Johnny




Johnny is the owner of Webtint and usually the sole contributer to the site (apart from the ocassional guest post).


Comments



developnew August 24, 2009 at 2:17 pm

Hi,

You code is very lengthy. you can create a jquery tab with following logic.


$(document).ready(function() {
$(".tabLink").each(function(){
$(this).click(function(){
tabeId = $(this).attr('id');
$(".tabLink").removeClass("activeLink");
$(this).addClass("activeLink");
$(".tabcontent").addClass("hide");
$("#"+tabeId+"-1").removeClass("hide")
return false;
});
});
});

[No direct links in comments, sorry]


    Jonathan August 24, 2009 at 2:30 pm

    Hello, I’m sorry my code doesn’t meet your standards, however they both work in the same way and although my code may be slightly longer, perhaps this way it’ll allow the user to learn more from this tutorial.


sunpietro August 25, 2009 at 1:59 pm

Hi,
your code doesn’t seem to work in IE.


    Jonathan August 25, 2009 at 8:31 pm

    Sorry about that. Fixed.


Richard Carr October 15, 2009 at 5:02 pm

Hi,

When I use this it seems to be stripping HTML out of everything in class=holder. I notice in your example that you don’t have HTML in there either and wondered if this is the way it’s meant to work?

In class=content the HTML is present fine eg.

N/A

But when this reaches class=holder it has become just

N/A

Apart from modifying class names carefully to avoid clashes with other stuff in my stylesheet, I basically just copied your code.

Any ideas would be much appreciated, I’m launching on Saturday!


Richard Carr October 15, 2009 at 5:04 pm

Sorry, the first comment demonstrating the HTML should include

N/A


Richard Carr October 15, 2009 at 5:05 pm

Gah ;-) Well basically there’s an ol and an li in the content div which doesn’t reach the holder div, it’s just plain text.

Thanks again.


Richard Carr October 15, 2009 at 5:15 pm

Ah, problem solved. A little research highlighted the text() function would strip HTML. I then noticed that in your step by step guide, you use the html() function but in the final code listing you’ve used text()

Problem = I copy and pasted the final listing.

Using html() it works fine. Might be an idea to change this little mistake?

Thanks for a useful bit of code anyway.



Twitted by titouille56


Tab switcher in jQuery « Open Source




Leave us a Comment



Put your name here:

Your email goes here:

Got a Website? Put it here (optional):

And finally, your comment:




Sponsors