How to Use jQuery to Create a Tabbed Interface in CSS3 - dummies

How to Use jQuery to Create a Tabbed Interface in CSS3

By John Paul Mueller

For some websites a tabbed interface is the best method to display the information. CSS3 has code to use the jQuery method to create a tabbed interface.

 // Create variables to hold temporary data.
 var TabHeads = ";
 var TabContent = ";
 // Obtain the XML data file and process it.
 $.get("XMLTabData.xml", function(data)
  // Locate each Heading entry and use it to
  // create a tab heading.
   TabHeads +=
   "<li><a href='" +
   $(this).attr("href") +
   "'>" + $(this).attr("caption") +
  // Append the data to the heading area.
  // Locate each Content entry and use it to
  // create the tab content.
   TabContent +=
   "<div id='" + $(this).attr("id") +
   "'>" + $(this).text() + "</div>";
  // Append the data to the tab content area.
  // Complete the process by displaying the
  // tabs.

The code begins by creating two variables: TabHeads and TabContent, to contain the data used to fill in the tabbed interface. This information is eventually added to two HTML tags, as shown here:

<div id="Tabs">
 <ul id="Headings" />

The get() method obtains the XML file, XMLTabData.XML, and places the content in data. What data contains is a fully formed XML file that’s passed to an anonymous function (one that has no name) that you define as: function(data){}. The function is executed when the data retrieval is complete, so it acts as a callback for an asynchronous data read.

All you need to know for the moment is that the XML file contains <Heading> elements that contain the data used to create the tab entries, as well as <Content> elements that contain the data placed within each tab. In this case, Tab 1 would be a heading and “This is some content for Tab 1.” would be content for that tab.


All of the heading information appears within the <Heading> elements. The code asks jQuery to find() each of the <Heading> elements and process them one at a time using the each() method. The each() method creates a loop that automatically provides access to individual <Heading> elements through the this variable. Tab headings are stored in an unordered list (<ul>), Headings, that’s already part of the HTML for the example page.

The content for each tab appears in <div> elements that are appended after the <ul> element, Headings. The content could be anything — including controls as used for the previous tabbed-interface example. The most important issue to consider is how to store information in the XML file. Be sure you escape any tags so that they’re not misinterpreted as XML elements.

As with the headings, the code uses find() to locate each of the <Content> elements in the XML file and convert them to the HTML required to create the tab content. The each() method creates the loop used to process each element one at a time.