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):

27-Jun-11 22:29
@RoryTheRoman: Sounds like a good plan! Glad you got it working.
Ian
18-Jul-11 10:10
Thanks for the script.

However I have come across one issue. Not sure if there is a solution.

If I have a Google map in one of the tabs, then only a fraction of the tab is loaded (top left). The JS for the map is initialized in the head after the init for the tabs. If I do it the other way round it makes no difference.

If I put the google map on the first tab all is fine and the tabs are all okay. However I would rather not have it on the first tab.

Is there any solution to this, where another JS is used within the tabs.

Thanks.
18-Jul-11 23:57
Hi Ian,

Hmm, not sure. You could try putting the call to init() at the end of your markup, before the </body> tag, instead of as an onload handler in the <body> tag?


<script>init();</script>
</body>
Ian
19-Jul-11 01:36
Thanks. But it didn't work - can't believe I am the only person with this issue, so will hunt around the net.

Keep up the good work
21-Jul-11 09:01
I was looking for an 'easy intro' to make a set of tabs in an HTML page and this is perfect. I am not looking for rocket science, but this would have taken me days to put together. Thanks a million for a great starter pack.
22-Jul-11 00:11
@Ian: It may be that the Google JavaScript is simply incompatible with the JavaScript to create the tabs. Or you may need to call a function in the Google JS to kick it off once the tab is loaded or displayed.

Also check your JavaScript console for errors.

@PEJK1953: You're welcome - thanks for your comment
Ian
24-Jul-11 10:46
Re jumping straight to a tab.

http://www.elated.com/forums/topic/4717/#post18005

I cannot get this to work & wanted to make sure I have the code in the correct place.

The 7 lines should look like (I assume)




// If a hash was supplied in the page URL,
// display the corresponding tab (if found)
if ( document.location.hash ) showTab( document.location.hash.substring(1) );
}

function showTab( selectedId ) {
if ( typeof selectedId != 'string' ) var selectedId = getHash( this.getAttribute('href') );
06-Aug-11 12:22
@Ian

Did you add onclick to the link you use to jump to a particular tab? I ran into that issue a few weeks ago - take a look at the following page and see the source of the link which is shown on the third tab where it says "Jump to GBP".

http://www.collents.eu/ge-economy.php

That link is like so:


<a href='#GBP' onclick='return showTab(this)'>Jump to GBP</a>
30-Oct-11 06:19
Dear Elated, I'm working on my websitemakerscript and want to sell it through the internet and would like to use this *tab*-script as mentioned above, but need to know if I may do so, i.e. what about license etc?

Hope to hear from you,

best regards,
mrsa
Asa
31-Oct-11 08:11
It is cool!
02-Nov-11 03:06
@mrsa: Fine by me! If you use the code then a credit/link to www.elated.com would be appreciated.

@Asa: Thanks
08-Nov-11 02:06
Great script!

Question, I have searched but had trouble finding a solution.
What is the easiest way to have the page load on the second tab.

I want to keep my tab order (1,2,3) but load with that second (middle) tab visible.

I've seen people changing the JS to allow for url's with the tab name, but that doesn't quite seem like the best solution for me.

Thanks in advance for your help!
11-Nov-11 03:28
dsol828: To display a different tab by default when the page loads, you should be able to change just these 2 lines of code:


if ( i == 0 ) tabLinks[id].className = 'selected';




if ( i != 0 ) contentDivs[id].className = 'tabContent hide';



Just change the 0 (zero) to the index of the tab you'd like to display (0=first tab, 1=second tab etc).
11-Nov-11 23:09
@matt

That did the trick! Thanks for the help!
17-Nov-11 15:00
I'm having problems jumping to a tab from another html page. The links at at the bottom right side of the index page. I've tried to modify the script as shown in earlier posts but it's not working for me. Please take a look and let me know how to fix. Thanks!

http://rancudo.com/testing/
18-Nov-11 00:47
@dsol828: You're welcome

@kcran: If you just make the 2 modifications shown in http://www.elated.com/forums/topic/4717/#post18005 then it should work.
18-Nov-11 07:16
Matt,
I had made the modification from post18005 already. The result is that it goes to the tab but does not load the related div content for that tab but just leaves an empty page.

Here's the header code from the page for you to examine...



<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 );


// If a hash was supplied in the page URL,
// display the corresponding tab (if found)
if ( document.location.hash ) showTab( document.location.hash.substring(1) );

}
}

// 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 ( id == "caracteristicas" ) tabLinks[id].className = 'selected';
i++;
}

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

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


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

function showTab( selectedId ) {
if ( typeof selectedId != 'string' ) 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>
21-Nov-11 23:54
@kcran: No idea then. That mod works for me. You might have other JS in the page that is conflicting. Try running init() at the end of your page within a script tag, instead of as the body load handler. That sometimes works. You can also use console.log() to log debug messages to the browser console, so you can see which parts of the code are (or aren't) running.
03-Jan-12 08:33
Thank you very much Matt -- this is Just what I was looking for and it works beautifully!

Do you know of a way to remove the hash from the URL? I have to work on that part now. Just trying to tweak the js and hoping that someone else has done it already.
11-Jan-12 16:43
@mfouwaaz: What URL? The URLs inside the links to the tabs? Why would you want to remove the hashes?

View all 240 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