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 is 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">
<tr>
<td id="a" class="tab">Tab A</td>
<td id="b" class="tab">Tab B</td>
<td id="c" class="tab">Tab C</td>
</tr>
</table>
<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 is the JavaScript code:

/*
Implementing Tab Menu with JavaScript
http://xahlee.org/js/tabs/a.html
Version 2006-02-18, 2023-03-08
*/

/* 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)
const xTabNames= ["a","b","c"];

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

    // go thru all tabs, if match, change tab to red, else silver

    // go thru all tabs, if match, change tab to red, else silver
    for (const xtab in xTabNames) {
        const xobj = document.getElementById(xTabNames[xtab]);
        if (xTabNames[xtab] == xcurFile) { xobj.style.backgroundColor="red";}
        else { xobj.style.backgroundColor="silver";}
    }

}

fSetTabColor();