JavaScript Tabs - Create Tabbed Web Pages Easily

Learn how to use JavaScript to create a tabbed Web page for holding lots of content. Full code included for copying and pasting into your website!

This tutorial shows how to create a Web page containing JavaScript-driven tabs. Each tab displays a separate chunk of content when clicked — perfect if your page needs to hold a large amount of content. It's also great for things such as multi-step ("wizard"-style) Web forms.

Click the link below to see a tabbed page in action:

JavaScript tabs screenshot

The JavaScript and markup are coded in such a way that the page degrades gracefully in browsers that don't support JavaScript.

In this tutorial you learn how this tabbed page is put together. You can then use the code and ideas to build your own tabbed Web pages. Let's get started!

Creating the HTML for the tabbed page

The HTML for the tabs and content is very simple. You store each tab's content within a div element with a class of tabContent and a unique id for reference. Here's the first of the 3 tab content divs in the example:


<div class="tabContent" id="about">
  <h2>About JavaScript tabs</h2>
  <div>
    <p>JavaScript tabs partition your Web page content into tabbed sections. Only one section at a time is visible.</p>
    <p>The code is written in such a way that the page degrades gracefully in browsers that don't support JavaScript or CSS.</p>
  </div>
</div>

The tabs themselves are simply links within an unordered list:


<ul id="tabs">
  <li><a href="#about">About JavaScript tabs</a></li>
  <li><a href="#advantages">Advantages of tabs</a></li>
  <li><a href="#usage">Using tabs</a></li>
</ul>

Give the ul an id of "tabs" so that the JavaScript code can locate it. Each link within the list links to its corresponding content div by referencing the id of the div ("about", "advantages", or "usage"). Since these are standard HTML links, they work fine even without JavaScript.

You can add as many tabs as you like to the page. Simply add a new content div and give it a unique id, then add a link to it within the tabs list.

Creating the CSS

Some CSS is needed in order to make the tabs look like tabs (and make them nice to look at):


body { font-size: 80%; font-family: 'Lucida Grande', Verdana, Arial, Sans-Serif; }
ul#tabs { list-style-type: none; margin: 30px 0 0 0; padding: 0 0 0.3em 0; }
ul#tabs li { display: inline; }
ul#tabs li a { color: #42454a; background-color: #dedbde; border: 1px solid #c9c3ba; border-bottom: none; padding: 0.3em; text-decoration: none; }
ul#tabs li a:hover { background-color: #f1f0ee; }
ul#tabs li a.selected { color: #000; background-color: #f1f0ee; font-weight: bold; padding: 0.7em 0.3em 0.38em 0.3em; }
div.tabContent { border: 1px solid #c9c3ba; padding: 0.5em; background-color: #f1f0ee; }
div.tabContent.hide { display: none; }

These CSS rules work as follows:

body
This sets a nice font and font size for the page.
ul#tabs
Styles the tabs list, turning off bullet points.
ul#tabs li
The display: inline; property makes the tabs appear across the page.
ul#tabs li a
Styles the links within the list. Each link is given a border around every side except the bottom, so that the active tab blends nicely with its content div below.
ul#tabs li a:hover
Highlights a tab when hovered over with the mouse.
ul#tabs li a.selected
Styles a selected tab by giving it a lighter background and bold text, and making it bigger. Notice that the bottom padding is increased to 0.38em to make sure that the tab blends with the content div.
div.tabContent
Sets a style for the tab content areas so that they match the tab design.
div.tabContent.hide
Used to hide unselected tabs.

Creating the JavaScript code

Finally, of course, you need JavaScript to make the tabs work. Here's what the JavaScript needs to do:

  • Attach a showTab() onclick event handler to each of the tab links.
  • Hide all content divs except the first, so that only the leftmost tab's content is visible when the page loads.
  • When a tab is clicked, showTab() displays the current tab content, and hides all other tab content divs. It also highlights the clicked tab and dims the other tabs.

The JavaScript kicks off by creating two arrays to hold the tab link elements and the content divs:


    var tabLinks = new Array();
    var contentDivs = new Array();

Four functions control the tabs:

  • init() sets up the tabs.
  • showTab() displays a clicked tab's content and highlights the tab.
  • getFirstChildWithTagName() is a helper function that retrieves the first child of a given element that has a given tag name.
  • getHash() is another short helper function that takes a URL and returns the part of the URL that appears after the hash (#) symbol.

Here's how these functions work.

The init() function

The first, and most complex, function is init(). It's called when the page loads, thanks to the body element's onload event:


  <body onload="init()">

Here's the function itself:


    function init() {

      // Grab the tab links and content divs from the page
      var tabListItems = document.getElementById('tabs').childNodes;
      for ( var i = 0; i < tabListItems.length; i++ ) {
        if ( tabListItems[i].nodeName == "LI" ) {
          var tabLink = getFirstChildWithTagName( tabListItems[i], 'A' );
          var id = getHash( tabLink.getAttribute('href') );
          tabLinks[id] = tabLink;
          contentDivs[id] = document.getElementById( id );
        }
      }

      // Assign onclick events to the tab links, and
      // highlight the first tab
      var i = 0;

      for ( var id in tabLinks ) {
        tabLinks[id].onclick = showTab;
        tabLinks[id].onfocus = function() { this.blur() };
        if ( i == 0 ) tabLinks[id].className = 'selected';
        i++;
      }

      // Hide all content divs except the first
      var i = 0;

      for ( var id in contentDivs ) {
        if ( i != 0 ) contentDivs[id].className = 'tabContent hide';
        i++;
      }
    }

This function does 3 things:

  1. It loops through all the li elements in the tabs unordered list. For each li element, it calls the getFirstChildWithTagName() helper function to retrieve the a link element inside. Then it calls the getHash() helper function to extract the part of the link's URL after the hash; this is the ID of the corresponding content div. The link element is then stored by ID in the tabLinks array, and the content div is stored by ID in the contentDivs array.
  2. It assigns an onclick event handler function called showTab() to each tab link, and highlights the first tab by setting its CSS class to 'selected'.
  3. It hides all content divs except the first by setting each div's CSS class to 'tabContent hide'.

So that init() runs when the page loads, make sure you register it as the body element's onload event handler:


  <body onload="init()">

The showTab() function

showTab() is called whenever a tab link is clicked. It highlights the selected tab and shows the associated content div. It also dims all other tabs and hides all other content divs:


    function showTab() {
      var selectedId = getHash( this.getAttribute('href') );

      // Highlight the selected tab, and dim all others.
      // Also show the selected content div, and hide all others.
      for ( var id in contentDivs ) {
        if ( id == selectedId ) {
          tabLinks[id].className = 'selected';
          contentDivs[id].className = 'tabContent';
        } else {
          tabLinks[id].className = '';
          contentDivs[id].className = 'tabContent hide';
        }
      }

      // Stop the browser following the link
      return false;
    }

The function extracts the selected ID from the clicked link's href attribute and stores it in selectedId. It then loops through all the IDs. For the selected ID it highlights the corresponding tab and shows the content div; for all other IDs it dims the tab and hides the content div. It does all this by setting CSS classes on the tab links and content divs.

Finally the function returns false to prevent the browser from following the clicked link and adding the link to the browser history.

The getFirstChildWithTagName() function

This helper function returns the first child of a specified element that matches a specified tag name. init() calls this function to retrieve the a (link) element inside each list item in the tabs list.


    function getFirstChildWithTagName( element, tagName ) {
      for ( var i = 0; i < element.childNodes.length; i++ ) {
        if ( element.childNodes[i].nodeName == tagName ) return element.childNodes[i];
      }
    }

The function loops through the child nodes of element until it finds a node that matches tagName. It then returns the node.

Learn about the childNodes and nodeName properties in the article Looking inside DOM page elements.

The getHash() function

The getHash() helper function returns the portion of a URL after any hash symbol. Used by init() and showTab() to extract the content div ID referenced in a tab link.


    function getHash( url ) {
      var hashPos = url.lastIndexOf ( '#' );
      return url.substring( hashPos + 1 );
    }

Putting it together

That's all there is to creating JavaScript-enabled tabs! Take another look at the demo again, and view the page source to see how the HTML, CSS and JavaScript code appear in the page:

  • The CSS and JavaScript go inside the page's head element. (You can move these into separate .css and .js files and link to them, if you prefer.)
  • The page's body element contains the onload event handler to trigger the init() function.
  • The tabs ul element contains the tab links.
  • Each tab's content is stored in a div with a class of tabContent and a unique id (referenced in the corresponding tab link).

Feel free to use this code in your own Web pages. Happy tabbing!

Follow Elated

Related articles

Responses to this article

20 most recent responses (oldest first):

01-Apr-13 05:37
JP,

I'm not sure if this will help but here's a working example of a page with a 2nd set of tabs - you will see them if you click on the "Services" tab (i.e. the 2nd tab - it may display in another language when you land there, depending on your browser's language preference setting).

http://cels.collents.eu

This example includes translation as well, by the way, and might give you an idea how to structure and translate your own site a little differently.

You can grab the jstab source file by looking at the page source code.

The translation system used is pretty much as is described here:

http://www.mind-it.info/2010/02/22/a-simple-approach-to-localization-in-php/?replytocom=23

Good luck!
JP
01-Apr-13 16:31
Hello Stanley,

Thank you very much for your quick feedback. I tried using that solution but somehow I could not get that to work either. The tabs were never styled as tabs but only as list items.

I think that is related to the page being hosted by Jimdo and them disabling a lot of script functionalities. I saw a solution by another Jimdo page that works based on jQuery. However, no matter how hard I tried, I could not get it to work.

Here is a link to the page with the working tabs hosted on Jimdo:
http://www.pictoo.be/wall-art/play/lego-vintage-1/#cc-m-product-5526255517

So if you could give me advice on how to implement that, I would be really grateful.

Thank you,
JP
25-Apr-13 07:34
This is a great post and I love this tabs example!

Is there a way to make the tabs scrollable? I have quite a few tabs and I'd like the user to be able to scroll to the right or left to get the tabe they are looking for.
29-Apr-13 23:27
@JP: Looks like that page uses jQuery UI's tabs, if that helps? http://jqueryui.com/tabs/

@chynawhyte: You could try wrapping the tabs in a parent div using overflow: scroll, or perhaps in an iframe?
07-Nov-13 20:06
hey mate thank for that grate help but i have an issue, for some reason, it's not switching from tab to tab. I've copy the code exactly and it's not working aim i missing some thing

here the java script


<script type="text/javascript">
//<![CDATA[
var tabLinks = new Array();
var contentDivs = new Array();
function init() {
// Grab the tab links and content divs from the page
var tabListItems = document.getElementById('tabs').childNodes;
for ( var i = 0; i < tabListItems.length; i++ ) {
if ( tabListItems[i].nodeName == "LI" ) {
var tabLink = getFirstChildWithTagName( tabListItems[i], 'A' );
var id = getHash( tabLink.getAttribute('href') );
tabLinks[id] = tabLink;
contentDivs[id] = document.getElementById( id );
}
}
// Assign onclick events to the tab links, and
// highlight the first tab
var i = 0;
for ( var id in tabLinks ) {
tabLinks[id].onclick = showTab;
tabLinks[id].onfocus = function() { this.blur() };
if ( i == 0 ) tabLinks[id].className = 'selected';
i++;
}
// Hide all content divs except the first
var i = 0;
for ( var id in contentDivs ) {
if ( i != 0 ) contentDivs[id].className = 'tabContent hide';
i++;
}
}
function showTab() {
var selectedId = getHash( this.getAttribute('href') );
// Highlight the selected tab, and dim all others.
// Also show the selected content div, and hide all others.
for ( var id in contentDivs ) {
if ( id == selectedId ) {
tabLinks[id].className = 'selected';
contentDivs[id].className = 'tabContent';
} else {
tabLinks[id].className = '';
contentDivs[id].className = 'tabContent hide';
}
}
// Stop the browser following the link
return false;
}
function getFirstChildWithTagName( element, tagName ) {
for ( var i = 0; i < element.childNodes.length; i++ ) {
if ( element.childNodes[i].nodeName == tagName ) return element.childNodes[i];
}
}
function getHash( url ) {
var hashPos = url.lastIndexOf ( '#' );
return url.substring( hashPos + 1 );
}
//]]>
</script>



here the html



<td >
<ul id="tabs">
<li>
<a class="selected" href="#cart">About JavaScript tabs</a>
</li>
<li>
<a href="#summary">Advantages of tabs</a>
</li>
</ul>

<div id="about" class="tabContent">
<h2>Product Info</h2>
<div>
<p>this is where we willl add to cart, price of info and how qunity amount info.</p>
</div>
</div>

<div id="advantages" class="tabContent hide">
<h2>Advantages of tabs</h2>
<div>
<p>here will be a quick summry on out product</p>
</div>
</div>



</td>


I'm kinda new to all this stuff i done a short 3 month course on everything and self thought my most of the thing I know.

so too some of you out there out of this may sound like a stupid question but please help me.
24-Nov-13 11:42
Hi,

I'm making a page with quite a few tabs and they go over the page width. How do you handle this elegantly? Here's my code--(some of the <div>s are empty cause this is a proof of concept for now but they will be filled in eventually).

Thanks a ton in advance!




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<!-- This page is copyright Elated Communications Ltd. (www.elated.com) -->

<title>JavaScript tabs example</title>

<style type="text/css">
body { font-size: 80%; font-family: 'Lucida Grande', Verdana, Arial, Sans-Serif; }
ul#tabs { list-style-type: none; margin: 30px 0 0 0; padding: 0 0 0.3em 0; }
ul#tabs li { display: inline; }
ul#tabs li a { color: #42454a; background-color: #dedbde; border: 1px solid #c9c3ba; border-bottom: none; padding: 0.3em; text-decoration: none; }
ul#tabs li a:hover { background-color: #f1f0ee; }
ul#tabs li a.selected { color: #000; background-color: #f1f0ee; font-weight: bold; padding: 0.7em 0.3em 0.38em 0.3em; }
div.tabContent { border: 1px solid #c9c3ba; padding: 0.5em; background-color: #f1f0ee; }
div.tabContent.hide { display: none; }
</style>

<script type="text/javascript">
//<![CDATA[

var tabLinks = new Array();
var contentDivs = new Array();

function init() {

// Grab the tab links and content divs from the page
var tabListItems = document.getElementById('tabs').childNodes;
for ( var i = 0; i < tabListItems.length; i++ ) {
if ( tabListItems[i].nodeName == "LI" ) {
var tabLink = getFirstChildWithTagName( tabListItems[i], 'A' );
var id = getHash( tabLink.getAttribute('href') );
tabLinks[id] = tabLink;
contentDivs[id] = document.getElementById( id );
}
}

// Assign onclick events to the tab links, and
// highlight the first tab
var i = 0;

for ( var id in tabLinks ) {
tabLinks[id].onclick = showTab;
tabLinks[id].onfocus = function() { this.blur() };
if ( i == 0 ) tabLinks[id].className = 'selected';
i++;
}

// Hide all content divs except the first
var i = 0;

for ( var id in contentDivs ) {
if ( i != 0 ) contentDivs[id].className = 'tabContent hide';
i++;
}
}

function showTab() {
var selectedId = getHash( this.getAttribute('href') );

// Highlight the selected tab, and dim all others.
// Also show the selected content div, and hide all others.
for ( var id in contentDivs ) {
if ( id == selectedId ) {
tabLinks[id].className = 'selected';
contentDivs[id].className = 'tabContent';
} else {
tabLinks[id].className = '';
contentDivs[id].className = 'tabContent hide';
}
}

// Stop the browser following the link
return false;
}

function getFirstChildWithTagName( element, tagName ) {
for ( var i = 0; i < element.childNodes.length; i++ ) {
if ( element.childNodes[i].nodeName == tagName ) return element.childNodes[i];
}
}

function getHash( url ) {
var hashPos = url.lastIndexOf ( '#' );
return url.substring( hashPos + 1 );
}

//]]>
</script>
</head>
<body onload="init()">
<h1>JavaScript tabs example</h1>

<ul id="tabs">
<li><a href="#about">Assgnment</a></li>
<li><a href="#english">English</a></li>
<li><a href="#german">German</a></li>
<li><a href="#danish">Danish</a></li>
<li><a href="#french">French</a></li>
<li><a href="#spanish">Spanish</a></li>
<li><a href="#dutch">Dutch</a></li>
<li><a href="#italian">Italian</a></li>
<li><a href="#japanese">Japanese</a></li>
<li><a href="#korean">Korean</a></li>
<li><a href="#chinese_simplified">Simplified Chinese</a></li>
<li><a href="#chinese_traditional">Traditional Chinese</a></li>
<li><a href="#1">Czech</a></li>
<li><a href="#2">Finnish</a></li>
<li><a href="#3">Hungarian</a></li>
<li><a href="#4">Norwegian</a></li>
<li><a href="#5">Ukrainian</a></li>
<li><a href="#6">Vietnamese</a></li>
<li><a href="#7">Thai</a></li>
<li><a href="#8">Swedish</a></li>
<li><a href="#9">Portuguese</a></li>
<li><a href="#0">Slovenian</a></li>
</ul>

<div class="tabContent" id="about">
<h2>About JavaScript tabs</h2>
<div>
<p>JavaScript tabs partition your Web page content into tabbed sections. Only one section at a time is visible.</p>
<p>The code is written in such a way that the page degrades gracefully in browsers that don't support JavaScript or CSS.</p>
</div>
</div>

<div class="tabContent" id="english">
<iframe src="https://app.io/7OkyqQ?orientation=portrait&device=iphone5" height="607px" width="291px" frameborder="0" allowtransparency="true" scrolling="no"></iframe>
</div>

<div class="tabContent" id="german">
<iframe src="https://app.io/7OkyqQ?orientation=portrait&device=iphone5" height="607px" width="291px" frameborder="0" allowtransparency="true" scrolling="no"></iframe>
</div>

<div class="tabContent" id="danish">
<iframe src="https://app.io/7OkyqQ?orientation=portrait&device=iphone5" height="607px" width="291px" frameborder="0" allowtransparency="true" scrolling="no"></iframe>
</div>

<div class="tabContent" id="french">
<iframe src="https://app.io/7OkyqQ?orientation=portrait&device=iphone5" height="607px" width="291px" frameborder="0" allowtransparency="true" scrolling="no"></iframe>
</div>

<div class="tabContent" id="spanish">
<iframe src="https://app.io/7OkyqQ?orientation=portrait&device=iphone5" height="607px" width="291px" frameborder="0" allowtransparency="true" scrolling="no"></iframe>
</div>

<div class="tabContent" id="dutch">
<iframe src="https://app.io/7OkyqQ?orientation=portrait&device=iphone5" height="607px" width="291px" frameborder="0" allowtransparency="true" scrolling="no"></iframe>
</div>

<div class="tabContent" id="italian">

</div>

<div class="tabContent" id="japanese">

</div>

<div class="tabContent" id="korean">

</div>

<div class="tabContent" id="chinese_simplified">

</div>

<div class="tabContent" id="chinese_traditional">

</div>

<div class="tabContent" id="1">

</div>

<div class="tabContent" id="2">

</div>

<div class="tabContent" id="3">

</div>

<div class="tabContent" id="4">

</div>

<div class="tabContent" id="5">

</div>

<div class="tabContent" id="6">

</div>

<div class="tabContent" id="7">

</div>

<div class="tabContent" id="8">

</div>

<div class="tabContent" id="9">

</div>

<div class="tabContent" id="0">

</div>



</body>
</html>

05-Jan-14 10:46
I dont now how to move to the next tab
coz i have too many lines i my page so I want to use link or button to go to the next page...

I tried this But It does not work...

<p><a onclick="return showTab(this)" href="#tab2">Go to the next tab</a></p>

If any one know the answer please reply
05-Jan-14 16:05
showTab(this) is simply going to show the same tab as you are clicking on, because the key word 'this' is a reference to itself.
05-Jan-14 20:31
Thanks 4 your reply chrishirst.....

But I want the exact answer How to get it.....


pls someone give me the answer...

[Edited by salmanmdz on 05-Jan-14 20:32]
06-Jan-14 09:17
And the remuneration for this contracted work will be??

[Edited by chrishirst on 20-Mar-14 09:39]
19-Mar-14 12:12
Hi Matt--
thanks so much for this script—I looked into a lot of ways of adding tabs and this is was the most flexible. I was able to get them to look exactly as I wanted.

My only problem is getting the page to load with a specific tab open. I've updated the script with the mods you mentioned to @mashdot, but it still doesn't work.

If I paste http://www.ghs.com/events/eelive_2014.html#kiosk
the page still loads with the first tab (#stage)!

I saw in another post that someone else had trouble with this and you suggested other JS running on the page could be conflicting. We have analytics and tracking JS that's included in the footer--could this be the source of the problem?
18-Jun-14 05:09
Can we assign the keyboard shortcuts for that TAB

Need yours Help on that


-Regard
Niraj
18-Jun-14 07:32
18-Jun-14 09:07
Its Highliting the TAB but it is not able to open the TAB
18-Jun-14 13:19
Use the onFocus event (http://www.w3schools.com/jsref/event_onfocus.asp) to activate the tab then.
07-Aug-14 02:23
Hi,

I managed to implement this tabs template successfully on my test website.

However, when trying to implement this on my actual site, the three tabs show at once and don't seem to hide regardless of clicking on another tab.

Please see link below to understand what I mean...

http://www.on-protein.com.au/index.php/categories/protein-powder-supplements.html#usage

What baffles me is that I've used the EXACT same coding in both websites, which are both hosted at the sample place and with the same coding even in the <head>. I'm using magento 1.7 and don't know what could be wrong.

Any help is appreciated. I'm trained in html but quite new to javascript and css.

Also, if anyone knows, why does the #usage keep appearing at the end of the URL?
08-Aug-14 04:36
In that source code I don't see anywhere that initialises the script, OTHER than a <body> tag that is in the WRONG PLACE

</div>
</div>
</div>
</div>
<body onload="init()">
<ul id="tabs">


And is going to do nothing at all.
08-Sep-14 02:17
Hi

I have come across some code which uses this way of making tabs. I works fine, but i have been assigned to make som ajustments on it. When there is nothing to show on a tab then the tab should be non visible.
I have made the showTab() return another class if it is to be non visible. It works fine, but when the user then set something so that the tab should be shown, then it doesnt, though it gets the right css style. I have to reload the whole page to make it work. Is there anyway to make this work so that you can control whether the tab should be shown dynamically

thanks in advance
Lars
08-Sep-14 06:56
Javascript has no way of determining if a particular element has or does not have 'content'.
08-Sep-14 08:58
Hi Lars

You do have a mechanism for the user to set something for the tab to be shown, even though the tab is invisible at that point, right?

I am thinking of AJAX and using the XMLHttpRequest object to refresh showTab() at that point. If that works then your tab should become visible. There seems to be a little bit of work to it but I think it should work.

Pardon me, I have not tested this but am just shooting my head off. I don't even have a system here. Obviously you know better on the subject but it maybe worth a try.

Good Luck!

View all 278 responses »

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page