This page is a tutorial on implementing tabs using JavaScript. Tabbed interface can also be done with just CSS. See: Implementing Tab Menu with CSS .
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.
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. 〔☛ 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>
When a tab is clicked, there are few things that must be done:
Here's the js code:
// -*- coding: utf-8 -*- // 2006-02-18 // 〈Implementing Tab Menu with JavaScript〉@ http://xahlee.org/js/tabs/a.html /* 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) { myObj.style.backgroundColor="red";} else { myObj.style.backgroundColor="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");}; setTabColor();
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.
blog comments powered by Disqus