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:
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
divbelow. 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()onclickevent 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 contentdivs. 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:
- It loops through all the
lielements in thetabsunordered list. For eachlielement, it calls thegetFirstChildWithTagName()helper function to retrieve thealink element inside. Then it calls thegetHash()helper function to extract the part of the link's URL after the hash; this is the ID of the corresponding contentdiv. The link element is then stored by ID in thetabLinksarray, and the contentdivis stored by ID in thecontentDivsarray. - It assigns an
onclickevent handler function calledshowTab()to each tab link, and highlights the first tab by setting its CSS class to'selected'. - It hides all content
divs except the first by setting eachdiv'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
headelement. (You can move these into separate.cssand.jsfiles and link to them, if you prefer.) - The page's
bodyelement contains theonloadevent handler to trigger theinit()function. - The
tabsulelement contains the tab links. - Each tab's content is stored in a
divwith a class oftabContentand a uniqueid(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):
The easiest way to create tabs with rounded corners is to use the CSS3 border-radius property. I covered this in our newsletter ( http://www.elated.com/newsletter/ ) a while back - here's what I wrote:
-----
1. Creating rounded corners with border-radius
Rounded borders around page elements have long been popular amongst web designers, but traditionally they're a pain to create. First you have to create the effect in Photoshop, then you have to slice up multiple background images for each element.
CSS3 promises to end all this hassle with the lovely border-radius property. This lets you create a border with rounded corners, and specify the radius of the corner curves. For example:
.mybox { border: 5px solid red; border-radius: 10px; }
At the time of writing, only Opera 10.5 supports border-radius as-is. Mozilla and WebKit browsers have their own versions (-moz-border-radius and -webkit-border-radius). So to get it to work in Opera, Firefox, Safari and Chrome you need to write:
.mybox { border: 5px solid red; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; }
Incidentally, you can also specify a radius for each corner individually, although sadly the syntax is completely different for each browser engine. (Can't these people agree on anything!) Here's how to set a rounded border just for the top right corner of an element:
.mybox { border: 5px solid red; border-top-right-radius: 10px; -moz-border-radius-topright: 10px; -webkit-border-top-right-radius: 10px; }
...
4. Getting it all working in IE
So now we come to the elephant in the room: Internet Explorer! How can we use these lovely CSS3 effects in this dear old browser? First of all, the good news is that IE9 will _probably_ support all these properties natively. For older versions, though, we'll need to resort to a bit of JavaScript cunning. Fortunately there's a great script out there that does all the hard work for us:
http://fetchak.com/ie-css3/
To use it, download the script and save it in the same folder as your Web page, then add the following property to the same selector(s) that use the CSS3 properties:
behavior: url(ie-css3.htc);
For example, here's how to create fully cross-browser rounded corners that work in Firefox, Safari, Chrome, Opera, and IE 6, 7 and 8:
.mybox { background: #fff; border: 5px solid red; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; behavior: url(ie-css3.htc); }
Have fun!
I can set a link within another page to go to a page that has tabs and have a specified tab open when the user arrives. That's cool! If I link to the tabbed page without a specific tab in the href code the page loads perefectly and I see the top of my page.
However when I specify a tab within the link (example: /folder/tabbed_page_name.aspx#tabID ) the page loads but is positioned down the page depending on which tab I specify - so the user does not see the top of the page. They are already scrolled down a bit. Is there a simple way to address this so that the page loads properly (not scolled down) but with the specified tab open?
Thanks!
My pages are built using aspx masters. I placed a topofpage anchor tag at the top inside the master like this:
<a name="topofpage"></a>
I have the init placed after my last div:
<script type="text/javascript">
init();
</script>
I simply modified this last piece of code to include window.location.hash = "topofpage" like this:
<script type="text/javascript">
init();
window.location.hash = "topofpage"
</script>
Now when the user clicks on a link that specifies a tab on the page, they arrive at the page with the proper tab opened and they are positioned at the top of the page.
@sixer: You can use the code fine within an existing page. What problem are you having exactly?
I have zero knowledge of js so I was hoping you might provide me the exact js code required to open a tab from an external link.
I have an email newsletter and when a particular story is selected I want the user to be taken to the browser where the tab with that story is opened and ready to read.
I require the code to use for teh link in the newsletter and any code changes required for the tabbed page itself.
Hope this makes sense.
Cheers, love your work.
Alan
I'm aware that you have answered this question in a previous post but to be honest I didn't understand the answer. I really do require something I can copy and paste and need to be told exactly where to place the code on the pages.
Thanks again,
Alan
[Edited by bgood on 16-Jul-10 14:58]
I had read your post but like I said above, I have no working knowledge of javascript and so it doesn't make a lot of sense when I read it.
Would it be possible to send me a stripped down working example (one html page with a link opening a specified tab on a different html page) so I can simply duplicate the parts that I require.
Cheers.
Is there anyone who can help me with a working example of using an external link to open a specific tab.
I need to link from a newsletter in Outlook Express to the tabbed webpage showing the relevant story.
I'm a graphic designer not a programmer so would really appreciate a little help getting this to work ASAP.
Thanks guys,
Just to add further to my posts above about seeking help with an external link.
This is an example of a tab which I would like to be opened upon arrival at the tabbed page
<li><a href="#three">Housing Direct</a></li>
This is the link I've been using to open the tab from an external link
index.htm#three
It does navigate to the correct story but then IE asks if I want to allow the content to open and when I select yes the page is refreshed and tab one is opened instead of tab three.
Can anyone help me to get this to work
Cheers
[Edited by armstra on 18-Jul-10 22:23]
I don't know what I did wrong but when i go to the #tab url it selects the tab defined but doesn't display tab content or unhighlight the default first tab.
<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 = ' ';contentDivs[id].className = 'tabContent hide';
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 );
}
jQuery(function( $ ){
$('ul#tabs').click( function() {
$.scrollTo( 'div#tabContentContainer', 600 );
} );
});
Great tabs, pity about the lack of feedback.
[Edited by armstra on 21-Jul-10 07:53]
I am new on this website as well new in web development. I learn css and html and quite fluent both of them but also learning java script and jquery . But I am not good in programming pls suggest me nice JavaScript book where I can find real programming I am so confuse and frustrate at the moment. I can do lower level programming but don’t have Idea about real programming pls suggest me some books or site name where I can learn deep knowledge of both of them.
Thanks
harshida
A good solid JavaScript book that I highly recommend is "JavaScript: The Definitive Guide":
http://www.amazon.co.uk/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/
Some good tutorial sites:
http://www.elated.com/articles/cat/javascript/ (our own tutorials)
http://www.w3schools.com/js/default.asp
http://articles.sitepoint.com/category/javascript
Hope that helps.
If you have specific questions please feel free to post them here:http://www.elated.com/forums/authoring-and-programming/
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 or two. Sign up now.
