jQuery Tabs

Create a Tabbed Interface Using jQuery

Tutorial Details
  • Difficulty: Intermediate
  • Completion Time: 1 Hour

Creating tabbed interfaces suddenly becomes a piece-of-cake when using the Tabs function in the jQuery UI library. It can be utilized to create completely unique interfaces without having to be a coding God – using only one line of code!


Step 1 – The Basics

In order to create our jQuery effects later in this tutorial, you will first need
the latest jQuery library, and
jQuery UI
with the ‘Core’ and ‘Tabs’ elements. If you’d prefer, you can
take these files from this tutorial’s source files.

Place these two files in a directory on your server. Also create the following files:

  • index.html
  • style.css
  • sprinkle.js

index.html will be for your HTML, style.css for the page styling
in CSS and sprinkle.js for our jQuery animations.

Inside index.html, lets open the document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery UI Tabs Demo</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery-ui-personalized-1.5.2.packed.js"></script>
<script type="text/javascript" src="sprinkle.js"></script>
</head>
<body>
</body>
</html>

Here, we set our DOCType to XHTML 1 Transitional, and import our CSS and JS files.
Be sure to change ‘jquery-1.2.6.min.js’ and ‘jquery-ui-personalized-1.5.2.packed.js’
if your jQuery files have a different file name.


Part A – ‘Vanilla’ Tabbed UI

This is one of the most common uses for a tabbed interface:

Step a.1 – The HTML

Between the <body> tags in our index file, type the following:

    <div id="tabvanilla" class="widget">

    <ul class="tabnav">
    <li><a href="#popular">Popular</a></li>
    <li><a href="#recent">Recent</a></li>
    <li><a href="#featured">Featured</a></li>
    </ul>

    <div id="popular" class="tabdiv">
    <ul>
    <li><a href="#">Welsh Zombie Sheep Invasion</a></li>
    <li><a href="#">Sheep Rising From The Dead</a></li>
    <li><a href="#">Blogosphere Daily Released!</a></li>
    <li><a href="#">Aliens Infiltrate Army Base In UK Town</a></li>
    <li><a href="#">U2 Rocks New York's Central Park</a></li>
    <li><a href="#">TA Soldiers Wear Uniforms To Work</a></li>
    <li><a href="#">13 People Rescued From Flat Fire</a></li>
    <li><a href="#">US Troops Abandon Afghan Outpost</a></li>
    <li><a href="#">Are We Alone? A Look Into Space</a></li>
    <li><a href="#">Apple iPhone 3G Released</a></li>
    </ul>
    </div><!--/popular-->

    <div id="recent" class="tabdiv">
    <p>Lorem ipsum dolor sit amet.</p>
    </div><!--/recent-->

    <div id="featured" class="tabdiv">
    <ul>
    <li><a href="#">Aliens Infiltrate Army Base In UK Town</a></li>
    <li><a href="#">Are We Alone? A Look Into Space</a></li>
    <li><a href="#">U2 Rocks New York's Central Park</a></li>
    <li><a href="#">TA Soldiers Wear Uniforms To Work</a></li>
    <li><a href="#">13 People Rescued From Flat Fire</a></li>
    <li><a href="#">US Troops Abandon Afghan Outpost</a></li>
    <li><a href="#">Sheep Rising From The Dead</a></li>
    <li><a href="#">Blogosphere Daily Released!</a></li>
    <li><a href="#">Apple iPhone 3G Released</a></li>
    <li><a href="#">Welsh Zombie Sheep Invasion</a></li>
    </ul>
    </div><!--featured-->

    </div><!--/widget-->

We begin by opening a DIV element with the ID of ‘tabvanilla’ and class of ‘widget’.
The ID will be used by jQuery in order to identify the area it should effect, and
the class is there for ease-of-use when styling.

Next is an unordered list with the Class of ‘tabnav’. The list contains the three
different tab names, each with a link in the style of “#xxxxx”. This is important
as these will be the IDs of the sections following.

The following div has an ID of ‘popular’, this matches with the link in the tabs
above. A ‘recent’ and ‘featured’ DIV is also included. These sections are what will
be shown/hidden by jQuery when the corresponding link it selected.

Depending on what content you have, you should have something like this:

Let’s make it look a little nicer, shall we?

Step a.2 – Styling

Add the following to your style.css file. It will be explained below.

    * {
    margin: 0;
    padding: 0;
    }

    body {
    font-size: 75%;
    color: #222;
    background: #ffffff;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    line-height: 1.6em;
    }

    .widget {
    width: 310px;
    margin: 20px;
    padding: 10px;
    background: #f3f1eb;
    border: 1px solid #dedbd1;
    margin-bottom: 15px;
    }

    .widget a {
    color: #222;
    text-decoration: none;
    }

    .widget a:hover {
    color: #009;
    text-decoration: underline;
    }

    .tabnav li {
    display: inline;
    list-style: none;
    padding-right: 5px;
    }

    .tabnav li a {
    text-decoration: none;
    text-transform: uppercase;
    color: #222;
    font-weight: bold;
    padding: 4px 6px;
    outline: none;
    }

    .tabnav li a:hover, .tabnav li a:active, .tabnav li.ui-tabs-selected a {
    background: #dedbd1;
    color: #222;
    text-decoration: none;
    }

    .tabdiv {
    margin-top: 2px;
    background: #fff;
    border: 1px solid #dedbd1;
    padding: 5px;
    }

    .tabdiv li {
    list-style-image: url("star.png");
    margin-left: 20px;
    }

    .ui-tabs-hide {
    display: none;
    }
  • * – Removes browser-set defaults for margins & padding.
  • body – Adds some basic text styling.
  • .widget – – A little bit of colour for distinguishing
    the Tab areaa.
  • .widget a – Link styling.
  • .tabnav li – Displays the list in a ‘inline’ (horizontal)
    manner. Gives a bit of padding between them.
  • .tabnav li a – This helps the tabs stand out from any
    other content.
  • .tabdiv – Gives the ‘content’ section a bit more style
    to separate it from the tabs.
  • .tabdiv li – Adds a custom image for lists inside the
    ‘content’ area. The star.png file can be downloaded from this tutorial’s
    source files.
  • .ui-tabs-hide – jQuery will apply a class of ‘ui-tabs-hide’

    to div’s not in use. This sets it so they will not display when jQuery tells it
    to.

You should now have something like the following:

It’s not going to win any design awards, but it’s the functionality we’re interested
in; so let’s dive into the jQuery.

Step a.3 – A Sprinkle of jQuery

Basically, jQuery allows the user to change the styling of elements on the page
in real-time. So in our case, we want jQuery to hide all elements inside of ‘div#tabvanilla’
except the one which corresponds with the tab which has been selected.

Open sprinkle.js and insert the following:

$(document).ready(function() {
	$('#tabvanilla > ul').tabs({ fx: { height: 'toggle', opacity: 'toggle' } });
});

THAT’S IT! But what does it mean?

$(document).ready(function() {

This line says “When the document is ready, do the following…” – ‘ready’
means when the very basics of the page has loaded (ie. Just the raw html); it will
not wait for images and video like if you used ‘onload’ instead.

$('#tabvanilla > ul').tabs({ fx: { height: 'toggle', opacity: 'toggle' } });

This tells the browser to look out of a ul list inside of an element
with the ID of tabvanilla, and to use the tabs
function to interact with. We also define two animation effects (fx:)
– toggling the height and opacity. This will cause the area to “fade and slide”
when switching tabs.

Give it a try. You should now have something similar to the image below; with a
smooth animation when switching tabs.


Part B – Video Selector

This is where you can really see bigger effects done using the same code. Next,
we’ll create a simple ‘Video Selector’ that can been seen in quite a few WordPress
templates recently.

Step b.1 – The HTML

Following on from the previous interface, add the following in your index.html
file.

    <div id="featuredvid" class="widget">

    <div class="fvid" id="vid-1">
    <object width="270" height="152">	<param name="allowfullscreen" value="true" />	<param name="allowscriptaccess" value="always" />	<param name="movie" value="http://www.vimeo.com/moogaloop.swf?clip_id=1211060&server=www.vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=00ADEF&fullscreen=1" />	<embed src="http://www.vimeo.com/moogaloop.swf?clip_id=1211060&server=www.vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=00ADEF&fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="270" height="152"></embed></object>
    </div>

    <div class="fvid" id="vid-2">
    <object width="270" height="219"><param name="movie" value="http://www.youtube.com/v/gPwmG3VuO_E&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.youtube.com/v/gPwmG3VuO_E&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="270" height="219"></embed></object>
    </div>

    <div class="fvid" id="vid-3">
    <object width="270" height="219"><param name="movie" value="http://www.youtube.com/v/p86BPM1GV8M&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.youtube.com/v/p86BPM1GV8M&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="270" height="219"></embed></object>
    </div>

    <ul class="vidselector">
        <li><a href="#vid-1"><span>Where The Hell Is Matt? (2008)</span></a></li>
        <li><a href="#vid-2"><span>Clint Eastwood's The Office</span></a></li>
        <li><a href="#vid-3"><span>Pale Blue Dot</span></a></li>
    </ul>            

    </div><!--/featuredvid-->

We begin by creating another ‘.widget’ div, but this time with the ID of ‘featuredvid’
(it’s important it has a different ID, as this is what jQuery uses to distinguish
tab sections from each other).

Next, we have three ‘.fvid’ divs with their own unique IDs. Inside each, is the
embed code for a video.

Finally, at the bottom is our ‘.vidselector’ list which will act as our Tabs. As
in the previous example, each list item’s link corresponds with one of the div’s
IDs.

You should have something similar to this:

Step b.2 – Styling

In the style.css file, following on from the CSS in our previous example,
insert the following:

    #featuredvid {
    text-align: center;
    }

    .fvid {
    margin-bottom: 5px;
    }

    .vidselector li {
    text-align: left;
    list-style: none;
    padding: 5px;
    background: #ffffff;
    border: 1px solid #dedbd1;
    text-transform: uppercase;
    margin-bottom: 5px;
    }
  • .vidselector li – Creates the boxed effect for the video
    link to go in.

Step b.3 – A Sprinkle of jQuery

Inside sprinkle.js, add the following before the line containing });
from the previous example.

$('#featuredvid > ul').tabs();

This tells your browser to use the tabs function to interact with the ul list inside
the #featuredvid element. We aren’t defining any animation effects this time as
due to the nature of the content in these boxes (video), effects tend not to work
very well.

One problem that occurs with this effect is that Internet Explorer will not pause
the video in a tab when you switch to another – causing the sound to continue playing
the background. This does not happen in Firefox, Opera or Safari.


Summary

Hopefully this tutorial has shown you that much more can be done with basic jQuery
functions than you initially thought. Check
out the official documentation for jQuery UI/Tabs
.

Both these effects have been incorporated into CocoaNews – the
first in a family of WordPress themes from vivaWP
coming mid-August.

Dan Harper is danharper on Themeforest
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://muiomuio.net Mário Andrade

    I’ve been trying to make the tabs work with jCarousel but can’t seem to make things coupe.

    Can’t seem to make jCarousel work with na updated version of jQuery and can’t make jCarousel work with the tabs.

    …help?

    Great tutorial by the way. Keep up the excelent work i’ve been producing

  • Ewan

    This is a great tut, but I am just learning Ajax. Does anyone know how I can link with a text link in one tabe to another?
    Please email me at e_arnolda@hotmail.com if anyone can help?
    Thanks in advance

  • Pingback: 30个动态标签设计 | 神农贝塔

  • Pingback: Retail Store Display

  • Denis

    I’m trying to put tabs into tabs .. :S .. but i cant get it right .. a mean that another tabbed menu would appear when you click on one outer tab like ‘recent’ here .. can anyone help me :) ..
    i’m a little new in this ..
    mail me: veqlargh@gmail.com

  • Denis

    sorry for previous post .. but i missed the one that HGN posted above ..

  • http://mohamedaslam.com Sri Lankan Best SEO

    Very useful tutorial..!
    Thank you very much…!

  • http://lizzeelike.wordpress.com/ Sabrina

    really nice. this is what i need. its very helpful.

    thanks
    Sabrina
    Bangladesh

  • Pingback: konflikt bei mehrfachem js-onload - jswelt - Forum (Javascript, PHP, MySQL, AJAX, Webdesign)

  • http://www.netondas.com Jay

    This is a really tight tut. Thanks!

  • Pingback: Tabs usando jQuery by nettuts | Blog Graphic

  • Pingback: 30+ Animated Tab-Based Interface and Accordion Scripts | SulVision

  • http://www.autogaming.net Bradley Wint

    Hey, very nice mod man, but I am having problems integrating it into my blog.

    I am trying to stick it into my sidebar, however when I do that, I get up to the stage where the CSS has an effect over it and styles is, showing the 3 panels one below the other with the appropriately colored borders etc, but I cannot seem to get it to function properly, even though I included both the jQueries and the sprinkle Java code. Any idea what I could be doing wrong?

  • Pingback: Ajax i webbdesign | Grafix Studio - webbdesign och grafik

  • http://www.ervinter.com Ervin Ter

    Nice. Thanks a lot.

  • sew few

    Very Nice tutz .Keep it up. I boookmark this page.THanx again.

  • http://www.sidekickflix.com MMA Video Clips

    Ive been looking for a way to create tabs for a while now. And Plus, its in Jquery, my favorite JavaScript library.

    Many thanks. Keep posting.

  • Marcus

    how how how do i put this into wordpress; do i have to create a new plugin or widget!!! my wordpress keeps breaking everytime i insert it into a sidebar!!!!

  • http://isle-blog.ru/ Igor

    “my wordpress keeps breaking”

    i take for my wordpress, look hear http://isle-blog.ru/ (my russian blog). But i can’t doing widget ??? i learn wordpress already about 1 month, if u want, i help u.

    I am just learning Ajax and wordpress – it work diffrent sites, but, i want say: IE8.0 – don’t work this… :( Opera, Mozilla – very good !

    tnx, now i want this paint… :)

  • http://www.cashforsurveysclub.com Cash For Surveys

    Great tutorial. Thanks very much. You answered the questions I was wondering about creating a tabbed interface.

  • rob

    Great Tutorial!

    Thanks

  • http://creditrapide.org/ Credit rapide

    Really good tutorial! Thanks for sharing.

  • Pingback: Welcome to Webmaster-Source 5.0

  • Pingback: jQuery For WordPress | Pixel Shoppe

  • http://tinyurl.com/6tr5ef escabclielm

    Hi there! I like your website ;)
    If u are looking for Paid Surveys this is the site for you.
    Start advancing your paychecks at http://tinyurl.com/9eeaop

  • Pingback: 30 Menus JS « Jagorh’s el Kernel del conocimiento

  • Gregory

    I am trying to implement this on an asp.net page. On the second tab there is a button which load data into a gridview. After this load the page jumps to the first tab and display the content of the first tab

    What must be done to keep the focus on the second tab and display the content of the second tab after the load?

  • Pingback: TheDaVis Blog — 30 menus basados en tabs y acordeones animados

  • rzepak

    Hi, i’ve got a problem with ui-tabs, it seems to load every link in tab by ajax, and I want to swith it off.. I tried everything and it doesn’t work.. please help

  • http://loymeetsworld.com loy

    I’ve tried the last step but I couldn’t make it look like the finished product. Can anyone please help me? Could other scripts affect it? I also used JDGallery.

  • Anna

    TWO TABBED INTERFACES ON THE SAME PAGE
    Could someone please let me know how to do this? As someone mentioned before, the first tabbed interface appears and functions normally, but the second does not. Apparently adding a new function to one of the js files solves this problem, but I have no idea how to do this.

    So, um, please help!

    What code do I have to put into what js file in order to make this work?

  • Pingback: 30+ Animated Tab-Based Interface and Accordion Scripts

  • http://www.whatsthelatest.net zplits

    Can this be added on wordpress 2.7?

  • Pingback: Rendi più dinamici i tuoi siti internet

  • Pingback: jQuery: Eine kleine Tutorial-Sammlung | Phlow

  • Pingback: The Power of WordPress and jQuery: 30+ Useful Plugins & Tutorials

  • elChe

    I tried this with the newest version of jquery and it didn’t work. I had to download your jquery files for this to work. Is it possible that I didn’t get the right personalized version?

  • elChe

    Also,

    I’m using swfobject on one of my tabs, it works correctly in IE, but the tab closes THEN the swfobjects disappear. How can I make them dissappear first?

  • http://thevintageacousticguitar.blogspot.com Vintage Acoustic Guitar

    Hai guys this is a quite conversational place i tink…if you guys interested in guitars visit my blog

  • Pingback: Beat and Byte » Crear tabs menus con Jquery

  • http://scyberspace.com Rene Merino

    This apparently works on wp 2.7.1 on my local sever but not online, it says that is null or the source is not defined, any reasons why?

  • Pingback: Free WordPress and jQuery: 25+ Useful Plugins & Tutorials | guidesigner.com

  • http://zandermartineau.com Zander Martineau

    If you need to implement the jQuery UI Tabs into a Textpattern site, check my post over at the Textpattern Support Forum- http://forum.textpattern.com/viewtopic.php?pid=201102#p201102

  • griefex

    Great tutorial!

  • Pingback: Muazzam Jquery Çalışmaları ! - Miraç Baran Satıç’ın Günlük Blogu

  • rick

    as elChe said

    “I tried this with the newest version of jquery and it didn’t work. I had to download your jquery files for this to work. Is it possible that I didn’t get the right personalized version?”

    Any one have any ideas?

  • HNEP

    Im trying to use some kind of tabbed interface in my blog with wordpress, but everytime i used, the tabbed didnt work.

    can someone help me?

  • http://webdevvote.com/Javascript/Create_A_Tabbed_Interface_Using_jQuery WebDevVote.com

    You are voted!
    Track back from WebDevVote.com

  • lane

    how would you change the speed of the animation?

  • Fred

    How can I use nested tabs? I add the second tabs to the sprinkle.js and although they appear fine, they don’t actually load any content inside of them…

    help please …