Easy Tabs via JavaScript

Following my mantra of keeping things as simple as possible while still making them able to be reused, I spent the past couple of days thinking of a way to code a tabbed interface that I was tasked with building.  Making the tabs wasn't such a big deal using a modified sliding doors approach, but I didn't want to take my usual approach to the JavaScript for switching between tabs.  In the past, I have used a Switch-Case loop to go through the tabs and either show them or hide them.  The problem with that is that I have to know what all the tabs are going to be and it's a real PITA to add or remove tabs later on.

This time I thought I would try something a little more OO.  The function I wrote is only 25 lines long without much error checking.  The beauty of this function is that I can reuse this function as often as I want.  Here is the function:

function showTab(listname,tabname) {
 var obj = document.getElementById(listname);
 var obj2 = obj.getElementsByTagName('li');
 var obj3;
 var obj4;
 
 for (i=0;i < obj2.length;i++) {
  obj3 = document.getElementById(obj2[i].id.substring(0,obj2[i].id.length-2));
  obj4 = obj2[i].getElementsByTagName('a');
  if (obj2[i].id == (tabname + "li")) {
   if (obj3.style.display != "block") {
    obj2[i].className = "ActiveTab";
    obj3.style.display = "block";

    obj4[0].className = "ActiveTab";
   }
  } else {
   if (obj3.style.display != "none") {
    obj2[i].className = "InactiveTab";
    obj3.style.display = "none";
    obj4[0].className = "InactiveTab";
   }
  }
 } 
}

The listname variable is the name of the UL that contain the tab being clicked on.  The tabname is the name of the DIV that is is going to be displayed.  The only naming requirement is that the LI that is the tab for a given DIV be the same name as the DIV plus 'li' on the end.  For example, if the DIV is named 'personal', the LI will be named 'personalli'.  This code also takes advantage of the className attribute to change the look and feel of the tabs and only changes the tabs that is being activated or deactivated, which should help with performance.  Using className is so much easier than changing all of the CSS settings individually and also makes it really easy to change the UI of the page.

<< Previous Document / Next Document >>
    Be the first in the world to comment on this entry!!!

Discussion for this entry is now closed.