Tabbed Menu with Pure JavaScript

By Xah Lee. Date: . Last updated: .

This page is a tutorial on implementing tabs using pure JavaScript, no CSS.

Note: You should use CSS instead. See: CSS: Tabbed Menu.

Tabs is a web design started in ~1999. For screenshots of popular sites using tab design, see: Web Design: Survey of Tab Style 2006.

Here's the basics.

Changing Button Appearance

For the looks, the buttons can be done as images. Each button having two image representations, one for On and one for Off. To change the state, just swap the image using DOM and JavaScript. (for how, see: Changing HTML Content with JavaScript) Alternatively, the buttons can also be done using style sheets. Each button is a textual link, with a background color and border. The change of button's state is done by change the background color. [see Changing a Element's Style with JavaScript]

On this page we use table tag. Here's the tab HTML code:

<table border="1">
<td id="a" class="tab">Tab A</td>
<td id="b" class="tab">Tab B</td>
<td id="c" class="tab">Tab C</td>
<script src="tab.js"></script>

Tab Switching Programing Logic

When a tab is clicked, there are few things that must be done:

  1. Open the page associated with the tab.
  2. Highlight that tab's color.

Here's the JavaScript code:

// -*- coding: utf-8 -*-
// 2006-02-18
// 〈Implementing Tab Menu with JavaScript〉@

/* Each tab is associated with a file. Each File name (without extension) must be the same as the tab's id. */

// a list of tab id. (file names)
var tabNames= ["a","b","c"];

function setTabColor() {
    // determine the current tab, from file path
    var fPath = document.location.pathname.split('/');
    var currentFile = (fPath[fPath.length-1]).split('.')[0]; // file name without extension

    // go thru all tabs, if match, change tab to red, else silver
    for (var aTab in tabNames) {
        var myObj = document.getElementById(tabNames[aTab]);
        if (tabNames[aTab] == currentFile) {"red";}
        else {"silver";}

// set a action for each tab
document.getElementById("a").onclick = function () {open("a.html","_self");};
document.getElementById("b").onclick = function () {open("b.html","_self");};
document.getElementById("c").onclick = function () {open("c.html","_self");};


In bottom few lines, we set the table cell tags to have a action. When clicked, it will open the page associated with that tab.

Then, “setTabColor” is called. It first get the file path, parse it to get the file name without the extension. Then, use that as id to set the correct tab's color.

If you have a question, put $5 at patreon and message me.