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

09-Aug-12 09:49
Love the code for tabs.
Have one question. How do you set the width of the tabs? I have tried to edit the tabcontent class and the only option I have is auto and inherit.
The data on the tab does not fill the whole tab and need to make the tab narrow and not fill the whole screen.
09-Aug-12 11:24
@Alexio

Just another javascript tabs fan passing through here... but I'll try and help.

You just need to edit the css, but it sounds like something's going wrong if you say your tabs are filling up the whole screen. Do your tabs look anything like the demo version here?

http://www.elated.com/res/File/articles/development/javascript/document-object-model/javascript-tabs/javascript-tabs.html

If you look at the source code for that page you'll see the 4th line in the css starting ul#tabs li a {

Just change it to read:

ul#tabs li a { color: #42454a; background-color: #dedbde; border: 1px solid #c9c3ba; border-bottom: none; padding: 0.3em 0.6em; text-decoration: none; }


You'll see the ul#tabs li a.selected line already has different padding set for the selected tab. You'll just need to play about with these to suit your own preference.

Just a thought but are you trying to edit the css directly in your page file, or through your web browser's element inspector?

If it's any help you can do what I do when I want to quickly experiment with changing stuff like this - if you have the Opera browser installed and then right click to view the page source you can make any changes you like in the HTML then click on the "Apply Changes" button at the top of the source viewer then go back to the tab with the page on to see what your changes did. If you refresh the page it'll just go back to whatever the original settings.

If you can't sort it out can you post a link to your page?

Hope this helps.
09-Aug-12 11:33
I think I should clarify a little better.
It is not the tab headings however it is the div.tabContent class that I want to modify. I need the tab content frame to be narrower. I have tried to adjust the right margin to make it more narrow and seems to work. However I think there should be a setting to set the width of the content page. It seem s to deafult to 100% width.
09-Aug-12 11:38
Try adding width to the tabContent class, like this (which works on Matt's demo page):

div.tabContent { border: 1px solid #c9c3ba; padding: 0.5em; background-color: #f1f0ee; width:75%;}
09-Aug-12 11:51
That seems to work however I am concerned with users having different size windows like they do in our work environment. Smaller windows will reduce the width of the frame and appear to change the layout of the content on the tab. Is there a way to hard code a set width and not a percentage of the visable window width? I am using the tabs on an electronic eform and other content of the form does not fill the width of the screen and is set at a fixed width. I need the tab content frame to match.
09-Aug-12 13:00
Yes, you can just set it to a fixed pixel size instead, e.g.

div.tabContent { border: 1px solid #c9c3ba; padding: 0.5em; background-color: #f1f0ee; width:450px;}
09-Aug-12 13:08
Worked like a charm.
Thanks alot!
09-Aug-12 13:13
You're welcome
21-Aug-12 08:56
Hey Matt, this was the gift which just keeps on giving.

Here's a shameless plug for my latest effort, javascript tabs full of multi-lingual goodness!

http://cels.collents.eu/

The link at the bottom of the page demonstrates how to open up another tab (in this case the contact tab).

In case you or anyone is interested the site uses a JSON language switcher which works pretty well - no ugly urls and the site appears by default in whichever language the visitor has set as the preferred language in their browser.

I've also got it to hide a tab for English readers and show it for everyone else, something I'll be expanding the use of with this particular site.
05-Sep-12 09:09
Great work - Thank you!

Sorry but maybe I missed it. I would like to use this for ASP.Net and am trying to figure out if I can switch to another tab from code in the code behind page?

Can anyone please help?

Thank you in advance.
05-Sep-12 15:56
You can't.

javascript is client-side and ASP.NET is server-side which runs and is completed before javascript even starts to load.
06-Sep-12 10:59
You can't? I know next to nothing about ASP.NET but I was bit surprised at that so I went looking. It says here that you can add javascript to your ASP.NET code.

http://ondotnet.com/pub/a/dotnet/2003/09/15/aspnet.html

Is it not possible with a bit of jiggery-pokery, or am I missing something?

(edit) "which runs and is completed before javascript even starts to load" may be what I'm missing!

[Edited by Stanley on 06-Sep-12 17:03]
07-Sep-12 13:12
Yes you can deliver javascript to the browser, in exactly the same way you can deliver HTML, CSS, Flash, Images, etc. etc.

In ASP.NET the "code behind" runs on the server before the resulting HTML is sent to the user agent.

ASP.NET cannot "switch tabs" without the user agent making another request to the server for the content to be displayed.
10-Sep-12 12:35
Hi Matt,

A big thank you for creating this script and posting so many helpful responses to questions. I've utilized the code on a website that is currently under development successfully but only noticed a small problem today when I put more content in one of the tabs.

The content (just text) runs to a goodish number of lines meaning you have to scroll down the page. I've placed a 'Go to the next tab' link at the bottom of this text as per your instructions.


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


This works just fine but unfortunately does not scroll the page up. Because there is less content on in the second tab users have to manually scroll up the page to view it. Not a massive deal i'm sure you will agree (!) but none-the-less not ideal.

I've spent a good few hours hunting around this forum and other websites experimenting but have yet to resolve it.

As this is the final tweak to what otherwise is a superb addition to my website I was hoping you would be able to suggest a solution.

Any help gratefully received!!

Thanks in advance.

Alex
11-Sep-12 07:08
@pepper116: You can use the scrollTo() method to scroll the viewport up to the top of your tabs after switching tabs:

http://www.w3schools.com/jsref/met_win_scrollto.asp
JP
31-Mar-13 14:42
Hi Matt,

I tried using your JavaScript tabbed content as a crutch to provide translations for article descriptions since the webshop I decided to use does not come with multilingual support. The problem now is that as soon as when I start using the script for a second product, the script does not work anymore but only works for the first product.

To solve this problem I dug all the way through this thread and stumbled over how you explained to use the script with several different tabbed areas on one page. I tried that solution (although it is like a hamster trying to build a spaceship with me - I am not programmer) but did not get it to work. It would also be good if the solution could work as independently as possible and would not need explicit variables to be declared and the likes.

When I looked around further, I also came across using CSS to solve my problem, but that seemed to work even less. Now I am pretty lost how I can actually solve this problem so that I can just add articles and such without having to keep track of what number of variable I call or something. Is using JavaScript even still the proper solution? The only thing I know is that I am pretty lost with this

Would you have a sixth grade solution for me how I can solve this? You can find the page I am working on under http://comficare.jimdo.com/deutsch/shop/

It would be really great if you could help me sort this out.

Thank you,
JP
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?

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