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

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?
02-May-12 21:37
Good script. Thank you for sharing it!
I believe I had it working fine at a point, but I made the page into a Microsoft Dynamic Web Template, and tested it again.

Now I'm getting a result where after choosing a tab, the page scrolls down. In Chrome and Safari it scrolls down to cover the header, on iPhone Safari and IE it scrolls down to the selected tab content...

Any ideas?

The page in question is below

http://traversecityinformation.com/xPHP/TraverseCityInformation/A%20Listing/index_copy(2).html

Thanks for your consideration.
05-May-12 13:01
NEVER MIND...
Although 5 out of 6 tabs had tab content on the page, I made the sixth a link to an outside page.

Lesson, don't take a line and link to another page.

Thanks again!
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

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