Skip to Main Content

Indiana University Indiana University


Using JavaScript to create a dynamic tab-based webpage

Have you ever been to a web page where you can click on buttons or tabs that swap content on the page without having to load an entirely separate web page? Have you ever wondered how to make your own page have similar behavior?
Well, there’s good news and bad news. The bad news is that you’re going to need to write a bit of javascript to get this to work, and if you don’t know javascript, I can understand your reflex to just close this tutorial right now– but hold on! The good news is that it’s simple and doesn’t require an in-depth understanding of javascript to get this working.

Prerequisites for this tutorial:
A moderate understanding of XHTML and CSS

In order to get started, create a new xhtml document using your favorite xhtml editor, and save it as anything you like (make sure it has either an htm or html file extension!), and copy the following code into your blank document:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />

<style type="text/css">
body
{
  text-align: center; /* to support older IE browsers */
  font: 100% calibri, verdana, sans-serif;
  margin: 0px; /* zero out margin and padding for best browser
compatibility */
  padding: 0px;
}
div#wrapper
{
  text-align: left; /* overrides the centering in the body rule */
  margin: 0px auto; /* centers the content on the browser window */
  width: 800px;
  background-color: #cddaff;
}
div#header
{
  text-align: center;
  background-color: #b2fadb;
}
table#buttons
{
  border-spacing: 25px 0px;
  margin: 0px auto;
  padding-bottom: 10px;
}
table#buttons td
{
  border: 1px solid #769185;
  margin: 0px 20px;
  width: 200px;
  height: 50px;
}
div#footer
{
  text-align: center;
  font-size: 70%;
  background-color: #b6c9ff;	
}
div.contentPage
{
  width: 700px;
  margin: 0px auto;
  border: dashed 1px #769185;
  padding: 10px;
  font-size: 120%;
}
h2, p
{
  margin-top: 0px;
  padding: 3px;
}
</style>

</head>
<body>
<div id="wrapper">
  <div id="header">
    <h1>Click a button to see each page</h1>
    <table id="buttons">
      <tr>
        <td>Home</td>
        <td>Contact</td>
      </tr>
    </table>
  </div> <!-- /header -->
  <div id="contentHome" class="contentPage">
  <h2>Welcome to Gary's tent shoppe</h2>
    <p>Hi, my name is Gary Gertmertin, and I love to sell tents. Ever since I was a wee lad, tents were beautiful pieces of human innovation to me. Over the years, I've slept in at least fifteen tents. Don't get me wrong, I hate camping, I just love tents.
    </p>
    <p>We sell all kinds of tents. There are doggy tents and tent mansions, complete with a swimming pool. If you want to know what types of tents we sell, then go to the contact information tab on this site, and shoot me an e-mail. We don't give out pictures, so don't bother asking.
    </p>
  </div>
  <div id="contentContact" class="contentPage">
    <h2>How to contact Gary</h2>
    <p>I refuse to use telephone technology. So don't ask for any telephone numbers.</p>
    <address>
      Gary Gertmertin<br />
      e-mail: gertymerty@example.com
    </address>
  </div>
  <div id="footer">
    <p>copyright 2011</p>
  </div>
</div>
</body>
</html>

From here on out, only add code that is bold and italicized.
Don’t worry if you don’t understand what all the CSS is doing; for this tutorial, what’s important to be aware of here is that there are multiple divisions (as coded with div elements, and in this example there are only two) that are intended to represent different sub-pages of this xhtml document, namely, a div element uniquely identified (with the id attribute) as “contentHome” and another with the id value “contentPage.”
Important: elements that you intend to control individually with javascript have to be referred to by the id attribute of the element, because unlike the class attribute, the id uniquely identifies the element and thus prevents ambiguity in the reference.
Go ahead and view the newly created page in a browser. You should see that both the home page and the contact page (the dashed line boxes in the periwinkle content area) are visible, stacked on top of each other. If there were more sub-pages, then there would be even more boxes here. There is a small bit of xhtml and css groundwork that we need to take care of before getting to the javascript. First, we’re going to prepare the “buttons.”
We want the user to be able to click on the “Home” and “Contact” “buttons” in the header section of the page to access the different sub-pages. Normally we would opt for anchor elements, but since we’re not actually leaving this page, we can just make the table data element behavior resemble anchor elements using css.
First, add the following declaration to the “table#buttons td” style rule in the embedded stylesheet:

 
table#buttons td 
{
  border: 1px solid #769185; 
  margin: 0px 20px; 
  width: 200px; 
  height: 50px; 
  cursor: pointer;
} 

Note: the “pointer” value does not work on IE4-5.5. Add “pointer: hand;” as well to accomodate those browsers.
Now, when the cursor moves over those table data elements, it becomes the hand which signifies a clickable area. We can improve this further by giving an even more pronounced visual cue. Anchor elements aren’t the only elements that the hover pseudo-selector works for. Let’s create some style for when the user hovers over a button. Type in the following style rule:

 

td:hover 
{ 
  background-color: #a1e2c6;
} 
 

You can add additional properties as you like to truly have a customized appearance. The user should now be given adequate visual cues that these table data elements are dynamic.
We’re almost ready to start writing some javascript to get the desired functionality to work. As it stands, all the sub-pages are visible onto the content pane when the webpage is accessed. We only want a sub-page to be visible if the corresponding button is clicked. Let’s use CSS to start hiding all the sub-pages by default.
To do this, add the following declaration to the “div.contentPage” style rule:

 
div.contentPage 
{ 
  width: 700px; 
  margin: 0px auto; 
  border: dashed 1px #769185; 
  padding: 10px; 
  font-size: 120%; 
  visibility: hidden; 
} 

If you refresh your page in the browser window, you’ll notice that while the sub-pages have been successfully hidden, they still take up the space in the content pane they did while they were visible. This will become especially problematic as the sub-pages become longer, or more sub-pages are added. To fix this problem, we have to separate the sub-pages from the standard document flow.
To remove an element from the document flow, we can change its position property using css. Add the following declaration to the “div.contentPage” style rule:

 
div.contentPage 
{ 
  width: 700px; 
  margin: 0px auto; 
  border: dashed 1px #769185; 
  padding: 10px; 
  font-size: 120%; 
  visibility: hidden; 
  position: absolute; 
} 

When you refresh the browser, the page should look as if it has no sub-pages. Now that these sub-pages are hidden away, we need to be able to get them back on command by clicking the buttons. This is where the javascript comes in. Are you ready?
Javascript is a fairly advanced topic, and this tutorial isn’t designed to lay down foundational knowledge for it. Rather, you should be able to learn just enough javascript to be able to integrate this functionality in your own site, and tweak it to your liking.
Add the following attribute to each opening td tag:

<td onmouseup="">Home</td>
<td onmouseup="">Contact</td>

onmouseup is an example of an event attribute. It will allow us to call javascript code when the user lets go of the left-click button on his or her mouse while the cursor is over a button. Other examples of event attributes are onclick, onmouseover, and onmouseout just to name a few. Clever use of these events will allow you to create a creative and dynamic website.
Write the following code as the value for the onmouseup attribute for the first td element:

<td onmouseup="showHide('contentHome','contentContact');">Home</td>

and the following for the second td element:

<td onmouseup="showHide('contentContact','contentHome');">Home</td>

Now, this shouldn’t really make any sense yet. Just recognize a couple facts here: showHide is the name of a function, and we are calling it here while passing in two, what are called, arguments– the strings “contentHome” and “contentContact,” which just so happen to be the names given to the buttons by their id attributes.
The showHide function works by passing in the element (by its id attibute value) you want to make un-invisible as the first argument, and whatever elements you want to hide or remain hidden are however many final arguments you want to pass, whether it’s the second argument, or third or fourth and so on. So in this case, when the user clicks the Home button, the contentHome div element becomes visible, and the contentContact becomes hidden or remains hidden, and vice versa for clicking the Contact button.
There’s only one problem though, and that is that the showHide javascript function does not exist yet. We have to write it, and that is just what we are going to do next. First, we are going to create an embedded javascript document within the head element of this page.
Scroll up to your head element where your embedded stylesheet exists. Add an opening and closing “script” tag pair somewhere directly within the scope of the head element.

 
<script type="text/javascript"> </script>

Start off by writing the following code within the script element:

function showHide()
{

}

The function keyword allows you to create a new function. We’ve named this function “showHide.” Everything between the curly brace pair will be executed when this function is called. Just assume that the parenthesis pair after “showHide” are required boilerplate code to get the function to work.
Inside of the curly braces type the following code:


function showHide() 
{ 
  var d = document; 
} 

We’ve now created a shorter name for document. Whenever we have to write “document,” we can simply write “d” instead. Each statement in javascript must be ended with a semicolon. Now, type the next line of code:

var d = document;
var args = showHide.arguments;

Like the previous line of code, we’ve assigned a shorter name for a longer sequence of characters to not only make typing more efficient, but more meaningful as well. By typing “showHide.arguments” we are accessing the list of arguments passed into the showHide function. The new variable “args” will now represent that list. We will now grab the first item from the list. Type the following line of code:

var d = document;
var args = showHide.arguments;
var idName = args[0];

We’ve successfully grabbed the first item of the list (item 0), and stored it in the variable “idName.” This is the name of the of element we wish to “show,” but not the element itself. We have to first retrieve the element, by writing the following line of code:

var d = document;
var args = showHide.arguments;
var idName = args[0];
var elementToShow = d.getElementById(idName);

We are passing our idName string into the getElementById function to grab the actual element we want to make visible, and we are storing it within the new variable we have named “elementToShow.”
Now that we have the element we’re looking for, to make it visibile, type the following code on a new line:

var d = document;
var args = showHide.arguments;
var idName = args[0];
var elementToShow = d.getElementById(idName);
elementToShow.style.visibility = 'visible';

At this point, the buttons should be able to make their respective sub-pages visible, but we have a couple problems. First, the sub-page made visibile will still be outside the document flow, which won’t work for this webpage design (the footer needs to be able to be pushed down). Second, we have no way of hiding any other sub-pages that might already be visible. Let’s address these problems now.
Type in the following code next:

var d = document;
var args = showHide.arguments;
var idName = args[0];
var elementToShow = d.getElementById(idName);
elementToShow.style.visibility = 'visible';
elementToShow.style.position = 'static';

The default css position property value is “static,” so this should now pop the sub-page back into the document flow. Excellent, the “show” part of the showHide function is now complete. It is now time for the “hide” part.
We will first start by declaring a new variable we plan to store the element we want to hide:

var d = document;
var args = showHide.arguments;
var idName = args[0];
var elementToShow = d.getElementById(idName);
elementToShow.style.visibility = 'visible';
elementToShow.style.position = 'static';

var elementToHide;

This part is a little trickier. For this specific webpage, since there are only two sub-pages, we could just do something very similar to what we did to show the elementToShow, but that would limit this function for webpages with only two sub-pages. We need to make this function more scalable, so as to allow any number of these sub-pages.
We will achieve this with a loop. For each iteration of the loop, we will hide the next argument in the list of arguments until the list is finished. To create this loop, write the following code:

var elementToHide;

for (var i = 1; i < args.length; ++i)
{

}

Without having explained the logic and syntax behind this code, the important thing to understand is that with this code, starting from the second argument, everything between those curly braces will be executed exactly as many times as there exist arguments remaining in the args list.
We will add three statements to this loop:

 
var elementToHide; 
for (var i = 1; i < args.length; ++i) 
{ 
  elementToHide = d.getElementById(args[i]);
  elementToHide.style.visibility = 'hidden';
  elementToHide.style.position = 'absolute';
} 

This should look similar to the code used to show the first argument. This time around, we are grabbing each of the remaining elements from the list, and overwriting the elementToHide variable each iteration with the next element in the list. Each element is set to be hidden again or remain hidden, and escape the document flow.
At this point, if all went well, you should be able to refresh the webpage in the browser window, and the dynamic functionality of the page should be complete.
If you want further practice, then try adding additional sub-pages, and buttons that correspond with them. The real challenge will come when you try to adapt this code to your own project. Hopefully this tutorial will have made the otherwise daunting javascript language manageable enough to create your own show/hide behavior to add to your website.


3 Responses to "Using JavaScript to create a dynamic tab-based webpage" to “Using JavaScript to create a dynamic tab-based webpage”

  1. Andy Says:

    Thanks. I’ve had an RSS feed for these posts for a while and with this post it has really payed off. This was very helpful information to me.

  2. passeport sante Says:

    it’s a bit hard to implement in a platform using this code.

  3. Brian Parker Says:

    Yes, JavaScript is a scripting language commonly implemented as part of a web browser in order to create enhanced user interfaces and dynamic websites. The most common use of JavaScript is to write functions that are embedded in or included from HTML pages and that interact with the Document Object Model (DOM) of the page.

Leave a Reply

Get Training Tips via RSS Subscribe to Entries feed or Read Comments via RSS Subscribe to Comments feed.