Examples of Using Tabs

In this section, we’ll put what you’ve learned about tabs to work.

Dynamic Creation of Tabs

We want to create a tab (and its contents) dynamically using JavaScript. In the code shown here, HTML code initially creates three tabs, while the JavaScript adds the fourth:

<script src = jquery.js></script>
<script src = jqueryui/js/jquery-ui-1.8.16.custom.min.js></script>

<link rel=stylesheet type=text/css
      href=jqueryui/css/smoothness/jquery-ui-1.8.16.custom.css />

<div id=tabs>
    <li><a href=#tab1>Tab 1</a></li>
    <li><a href=#tab2>Tab 2</a></li>
    <li><a href=#tab3>Tab 3</a></li>
  <div id=tab1>Contents of first tab</div>
  <div id=tab2>Contents of the second tab</div>
  <div id=tab3>Contents of the third tab</div>


$("#tabs").tabs ({
  fx : { opacity : "toggle" },
}).tabs ("add", "#tab4", "Tab 4");

$("<i>Contents of the fourth tab</i>").appendTo ("#tab4");


Notice how we have chained the first tabs () method with the second. The first tabs () method is necessary because it transforms the HTML code we’ve written into a code that displays tabs (with CSS classes that jQuery UI automatically adds), while the second allows the "add" action, which adds the tab at the bottom of the list.

The tab is created by jQuery UI, as well as the <div> corresponding to its content. This content is empty, so we add the last appendTo () statement to add content.

The result is shown in Figure 2-5.

Figure 2-5. The fourth tab is created dynamically.

Modifying the Contents ...

Get jQuery UI now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.