A page with tables

You know how to create pages, add text, interact with the user, and add images. We’re on our way to making complete Web sites.

This lesson looks at the HTML tags for tables. Tables make it easy to present data in rows and columns. Here’s an example:

Dog Size Breed
Kieran Large Lab
CC Medium Sheltie
Renata Medium Coonhound/lab mix

Tables are important for many Web sites. Use them for schedules, price lists, statistical information, ... anything you like.

This lesson will show you how to create tables, style them, and let the user interact with them.

Let’s go!

Basic tables

This page’s goals

By the end of this page, you should:

  • Be able to create a basic table.
  • Add a header and footer.

Basic tables

Here’s a table listing some university classes:

Table example

Figure 1. Table example

It’s hard to see the rows and columns, so let me add some lines.

Table example with borders

Figure 2. Table example with borders

You can see that the table has two rows and three columns. That’s what makes a table a table: rows and columns.

Here’s the code for the table (like Figure 1, with no borders).

<table>
  <tr>
    <td>DOG 101</td>
    <td>Introduction to the modern dog</td>
    <td>MW 9:00am - 11:00am</td>
  </tr>
  <tr>
    <td>DOG 110</td>
    <td>Dogs in the ancient world</td>
    <td>M 6:30pm - 9:30pm</td>
  </tr>
</table>

Figure 3. Code for a simple table.

The whole thing is surrounded with <table> tags: lines 1 and 12.

Each row is inside a <tr> tag pair. The first row is from lines 2 to 6, the second from lines 7 to 11.

Inside each <tr>, there is a <td> pair for each table cell. The “d” in <td> stands for “data.” There’s one <td> for each column.

Here’s some more code:

<table>
  <tr>
    <td>a</td>
    <td>0.00</td>
    <td>0.01</td>
    <td>0.02</td>
    <td>0.03</td>
    <td>0.04</td>
    <td>0.05</td>
  </tr>
  <tr>
    <td>0.0</td>
    <td>0.0000</td>
    <td>0.0040</td>
    <td>0.0080</td>
    <td>0.0120</td>
    <td>0.0160</td>
    <td>0.0199</td>
  </tr>
  <tr>
    <td>0.1</td>
    <td>0.0398</td>
    <td>0.0438</td>
    <td>0.0478</td>
    <td>0.0517</td>
    <td>0.0557</td>
    <td>0.0596</td>
  </tr>
  <tr>
    <td>0.2</td>
    <td>0.0793</td>
    <td>0.0832</td>
    <td>0.0871</td>
    <td>0.0910</td>
    <td>0.0948</td>
    <td>0.0987</td>
  </tr>
  <tr>
    <td>0.3</td>
    <td>0.1179</td>
    <td>0.1217</td>
    <td>0.1255</td>
    <td>0.1293</td>
    <td>0.1331</td>
    <td>0.1368</td>
  </tr>
</table>

Figure 4. Another table

It looks like this in a browser:

Another table

Figure 5. Another table – rendered

Extra math points if you know what this is, or can figure it out. Hint: it’s part of a probability distribution.

Exercise: Color table

Create a table that looks like this:

Color table

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Here’s the table of university classes again:

Table example

Figure 1 (again). Table example

It might help to add a header, so users know what the columns are. A footer can come in handy, too. How about this:

Table example with header and footer

Figure 6. Header and footer

Here’s the code:

<table>
  <thead>
    <tr>
      <th>Course code</th>
      <th>Title</th>
      <th>When offered</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>DOG 101</td>
      <td>Introduction to the modern dog</td>
      <td>MW 9:00am - 11:00am</td>
    </tr>
    <tr>
      <td>DOG 110</td>
      <td>Dogs in the ancient world</td>
      <td>M 6:30pm - 9:30pm</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3">Times subject to change.</td>
    </tr>
  </tfoot>
</table>

Figure 7. Code for header and footer

The table is divided into three parts: the header, the body, and the footer. The header is from lines 2 to 8. The body is from lines 9 to 20. The footer is from lines 21 to 25.

The header uses the tag <th> instead of <td>. The h stands for “header,” as you might imagine. By default, browsers render <th> as centered and bold.

For the footer, I could have left out the colspan:

<tfoot>
  <tr>
    <td>Times subject to change.</td>
  </tr>
</tfoot>

Figure 8. Bad footer

It would have looked like this:

Bad footer rendered

Figure 9. Bad footer – rendered

The browser expanded all of the cells in the first column to fit the content in the footer. That gives too much space in the first two rows of the first column.

Instead, I did this:

<tfoot>
  <tr>
    <td colspan="3">Times subject to change.</td>
  </tr>
</tfoot>

Figure 10. Good footer

colspan="3" tells the browser that the first <td> covers three columns in the table. There’s enough room for “Times subject to change.” W00f!

Exercise: Color table with header and footer

Add a header and footer to your color table:

Color table with header and footer

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page you learned how to create a basic table, and add a header and footer.

What now?

Let’s style the tables. We’ll give them a CSS makeover.

Styling tables

Where are we?

You’ve learned how to create basic tables, with rows and columns. You know how to add headers and footers. But they don’t look great. Let’s fix that with CSS.

This page’s goals

By the end of this page, you should:

  • Be able to add spacing around tables and cells.
  • Be able to add borders and background colors.
  • Be able to style a table’s header and footer separately from its body.
  • Be able to add striping to a table using jQuery.

Add spacing

Here’s the university course list from earlier:

University courses

Figure 1. University courses

Here’s the code:

<table>
  <thead>
    <tr>
      <td>Course code</td>
      <td>Title</td>
      <td>When offered</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>DOG 101</td>
      <td>Introduction to the modern dog</td>
      <td>MW 9:00am - 11:00am</td>
    </tr>
    <tr>
      <td>DOG 110</td>
      <td>Dogs in the ancient world</td>
      <td>M 6:30pm - 9:30pm</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3">Times subject to change.</td>
    </tr>
  </tfoot>
</table>

Figure 2. Code for university courses

The table is made up of boxes:

Table boxes

Figure 3. Table boxes

As you can see, the table is one giant box, with smaller boxes within it. Each box is a cell in the table.

Suppose I want to add more space around the table and the cells:

With spacing

Figure 4. With spacing

I’d change the code to:

...
<style type="text/css">
  #table1 {
    margin: 20px;
    border-spacing: 10px;
  }
  #table1 td {
    padding: 10px;
  }
</style>
...
<table id="table1">
...
</table>
...

Figure 5. Table spacing with CSS

Line 4 adds space around the edges of the entire table. Line 5 adds space around the outside of the cells. Line 8 adds spacing inside the cells, between the edges of the cells and their contents.

Borders and background colors

Suppose I wanted to make the table look like this:

Adding colors

Figure 6. Adding colors

Here’s some code:

...
<style type="text/css">
#table1 {
  color: #585858;
  background-color: #FFFFEE;
  border: 2px solid #683900;
  margin: 10px;
  border-spacing: 2px;
}
#table1 td {
  border: 1px dotted #AB5500;
  padding: 2px;
}
</style>

Figure 6. Code to add colors

There’s a lot you can do with colors and spacing. You can experiment with Somacon’s HTML and CSS Table Border Style Wizard.

When you use <thead>, <tbody>, and <tfooter> tags, you can easily give the header and footer of a table a different look from the footer.

Suppose I wanted to make this:

Header and footer styling

Figure 7. Header and footer styling

Here’s the entire page:

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Table example</title>
    <style type="text/css">
      #table1 {
        color: #585858;
        border-spacing: 5px;
      }
      #table1 tbody td {
        background-color: #FFFFCC;
        padding: 4px;
      }
      #table1 thead td, #table1 tfoot td {
        color: #FFFFCC;
        background-color: #683900;
        padding: 4px;
      }
    </style>
  </head>
  <body>
    <table id="table1">
      <thead>
        <tr>
          <td>Course code</td>
          <td>Title</td>
          <td>When offered</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>DOG 101</td>
          <td>Introduction to the modern dog</td>
          <td>MW 9:00am - 11:00am</td>
        </tr>
        <tr>
          <td>DOG 110</td>
          <td>Dogs in the ancient world</td>
          <td>M 6:30pm - 9:30pm</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="3">Times subject to change.</td>
        </tr>
      </tfoot>
    </table>
  </body>
</html>

Figure 8. Code for header and footer styling

The rule in lines 7 to 10 sets text color and border spacing for the entire table. Lines 11 to 14 styles the body of the table. Lines 15 to 19 style the header and footer, giving them the same style.

Look at the selector on line 15:

#table1 thead td, #table1 tfoot td

The comma (,) in the middle says that the rule should be applied to two things. The first thing is the set of <td> tags in the <thead> of the element with the id of table1 (remember: # says “look at the id attribute”). The second thing in the selector – after the comma – is the set of <td> tags in the <tfoot> of the element with the id of table1.

Exercise: Styling the color table

Style your color table so that it looks like this:

Styled color table

Upload your solution to your server. Enter the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Table striping

On the previous page, we had a table of numbers that looked like this:

Another table

Figure 9. Table o’ numbers

Suppose I wanted to make it look like this:

Striping

Figure 10. Striping

Easy to do with some jQuery magic. Here’s the code for the page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Normal distribution</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <style type="text/css">
      body {
        font-family: Verdana, Helvetica, sans-serif;
        font-size: 12px;
        color: #585858;
      }
      .probability_table {
        border-spacing: 4px;
        text-align: right;
      }
      .probability_table td {
        padding: 4px;
      }
      .probability_table thead {
        color: white;
        background-color: #585858;
      }
      .odd_row {
        background-color: #DDDDDD;
      }
    </style>
    <script type="text/javascript">
      $(document).ready(function() {
        $(".probability_table tbody tr:odd").addClass("odd_row");
      });
    </script>
  </head>
  <body>
    <table class="probability_table">
      <thead>
        <tr>
          <td>a</td>
          <td>0.00</td>
          <td>0.01</td>
          <td>0.02</td>
          <td>0.03</td>
          <td>0.04</td>
          <td>0.05</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>0.0</td>
          <td>0.0000</td>
          <td>0.0040</td>
          <td>0.0080</td>
          <td>0.0120</td>
          <td>0.0160</td>
          <td>0.0199</td>
        </tr>
        <tr>
          <td>0.1</td>
          <td>0.0398</td>
          <td>0.0438</td>
          <td>0.0478</td>
          <td>0.0517</td>
          <td>0.0557</td>
          <td>0.0596</td>
        </tr>
        <tr>
          <td>0.2</td>
          <td>0.0793</td>
          <td>0.0832</td>
          <td>0.0871</td>
          <td>0.0910</td>
          <td>0.0948</td>
          <td>0.0987</td>
        </tr>
        <tr>
          <td>0.3</td>
          <td>0.1179</td>
          <td>0.1217</td>
          <td>0.1255</td>
          <td>0.1293</td>
          <td>0.1331</td>
          <td>0.1368</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

Figure 11. Striping page

Let’s go over the code. Lines 35 to 85 are the HTML for the table. I gave the table a class of probability_table.

Renata
Renata

Can I ask a question?

Kieran
Kieran

Indeed!

Renata
Renata

In other examples, you gave tables ids. But you’ve given this one a class. Why?

Kieran
Kieran

Good question. Let me explain.

Renata noticed that in other cases, I’ve given tables ids, like this:

<table id="table1">

Why use class here? Because when I imagine a site that has number tables, there could be more than one number table on each page. Remember that I can only use a particular id once on a page. But I can use the same class many times. By using class, I can have one set of CSS rules that will apply to all of the number tables on a page.

This is how Webers think about their work. “Since there can be more than one number table on a page, how should I code it to reduce development costs, and make changes to the site easy and cheap?” Your employers and clients will thank you for thinking this way.

Let’s go back to the code. You can see that I’ve added <thead> (line 36) and <tbody> (line 47) tags, so I can style those parts separately. This table doesn’t need a separate footer.

Here’s how the header is colored:

.probability_table thead {
  color: white;
  background-color: #585858;
}

Figure 12. Header colors

The text color is white, and the background is gray.

Any color code that has the same values for red, green, and blue will show as gray. The lower the value you use, the darker the gray. So rgb(50, 50, 50) is a dark gray, and rgb(200, 200, 200) is a lighter gray.

The striping is done with jQuery. Let’s focus on that:

...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style type="text/css">
...
  .probability_table td {
    padding: 4px;
  }
...
  .odd_row {
    background-color: #DDDDDD;
  }
</style>
<script type="text/javascript">
  $(document).ready(function() {
    $(".probability_table tbody tr:odd").addClass("odd_row");
  });
</script>
...

Figure 13. Striping with jQuery

Line 2 adds the jQuery code, fetching it from Google. You need to do this before you can do any jQuery magic.

Lines 14 to 16 do the striping. Remember that $(document).ready() runs when the page has been loaded. It contains one line:

$(".probability_table tbody tr:odd").addClass("odd_row");

The selector says “Find every element with a class of probability_table. Within them, find every <tbody> element. Then select all of the odd numbered <tr>s.”

Then, for all of the elements that the selector returns (which will be all the odd numbered rows in elements with a class of probability_table), add the class odd_row. This class is defined in lines 9 to 11. It sets the background color to gray.

Renata
Renata

Another question.

Kieran
Kieran

What’s that?

Renata
Renata

You have <thead> and <tbody> in the HTML. So you can style the table head and body separately.

Kieran
Kieran

Right.

Renata
Renata

But look at the rule at lines 5 to 7. It has a <td> in it, but no <thead> and <tbody>. What’s the deal?

Kieran
Kieran

Ooo, another good question.

The rule in lines 5 to 7 applies to all <td>s in the table, no matter where they are. If I were to change line 6 to, say, 10 pixels, all the cells in the table would change, no matter whether they were in the head or the body of the table. This helps me keep things consistent.

CC
CC

Hmm, let’s see if I have things straight.

Kieran
Kieran

OK.

CC
CC

Can we look at the output again?

Kieran
Kieran

OK. Here it is.

Striping

Figure 10 (again). Striping

CC
CC

The cell with the “a” in it, the one in the top left. It looks like it has a gray background, white text, and 4 pixels of padding. Is that right?

Kieran
Kieran

Yes.

CC
CC

But no single rule specifies that. So are the rules combined?

Kieran
Kieran

Yes! The font-family and font-size come from one rule. The text-align comes from another. The padding comes from yet another. And a different rule gives the colors.

This is normal in CSS work. The Weber figures out what aspects of a look go with what elements. The typeface is to be the same on the entire page, so it gets attached to the <body> tag. The text-alignment is to be the same for the entire table, so it gets attached to the <table> tag.

CC
CC

I can see how that would make the page easier to change. Like, change one number on line 6, and the padding changes in the entire table. For the header and the body. And the footer, if there was one.

Kieran
Kieran

Right!

CC
CC

But that’s a lot to think about.

Kieran
Kieran

It seems like that when you’re learning, but not when you actually do it. CSS fits naturally with the way we think about tables, with things (like cells) inside things (like rows) inside things (like a table body). It ends up being intuitive, once you’ve done it a few times.

Exercise: Striping the color table

Make your color table look like this:

Striping

Hint: odd or even?

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page, you learned how to:

  • Add spacing around tables and cells.
  • Add borders and background colors.
  • Style a table’s header and footer separately from its body.
  • Add striping to a table using jQuery.

W00f!

What now?

How about a table for your eMe?

eMe: Your own table

Where are we?

You know how to make a table. You know how to style one. Time to make one for your own site.

What about?

Make a table about something on your interesting stuff list. For example, I might make a table about Buffy, like this:

Season U.S. ratings
1 3.7 million
2 5.2 million
3 5.3 million
4 4.7 million
5 4.4 million
6 4.6 million
7 3.6 million

Choose something, and make a table about it. Style it any way you want. Border or not. Background color. Whatever suits your fancy.

If you want, you can put images in your table.

Summary

  • You made a table for your eMe.

What now?

Let’s make an interactive table. The user clicks, and something happens.

Interactive tables - sorting

Where are we?

You know how to create and style tables. Let’s make tables interactive.

This page’s goals

By the end of this page, you should be able to make a table sortable. Users will be able to click on table columns to sort tables the way they want. You’ll use a jQuery plugin to do the work.

Understanding the task

Suppose Ted and Fred both want to buy dog toys. Ted wants the best he can find. Fred just wants something cheap.

Ted and Fred visit a site that sells dog toys. Ted wants a good toy, so he’d like to see the toys with the highest ratings listed first:

Sort by rating

Figure 1. Sort by rating

Fred wants to see the cheapest toys listed first:

Sort by price

Figure 2. Sort by price

We can give them both what they want by letting them choose how they want the table sorted. They could click on the column titles to sort. You can try the page.

jQuery plugins

A plugin is a JavaScript program that you can add to jQuery. It extends jQuery, that is, makes jQuery do something extra. There are hundreds of plugins, for everything from graphing, image handling, chat, ..., well, you name it. You can check the list.

There are three steps to using a plugin:

  1. Add the plugin JS file to your page.
  1. Set up the HTML and CSS the plugin needs.
  1. Call the plugin.

Adding the plugin

A plugin is just a JavaScript file. You add it to your page like any other JS file: with a <script> tag in the header.

Set up your HTML and CSS

Some plugins require special set up in HTML or CSS. But you’ve seen that before. Take the jQuery function addClass(). (It’s a normal part of jQuery, not from a plugin.) It adds a class to an element.

Suppose we had this code:

$("#best_dog").addClass("champion");

It tells JS to find an element with the id best_dog, and add the class champion to it.

The code isn’t going to work if you haven’t already set up an element with the id best_dog in the HTML, and created a class called champion in the CSS.

The same thing with plugins. You can’t tell a plugin to graph some data if you don’t tell it what data to graph. You can’t tell a plugin to shrink an image if you don’t tell it what image to shrink.

That’s what I mean by “set up your HTML and CSS.” You need to prepare the things that the plugin will manipulate.

Calling the plugin

Once you’ve added a plugin, you treat it as if it was built-in to jQuery. Most plugins create new functions, like drawGraph() or playSound(). You call the functions, as if they were part of jQuery to begin with.

Using tablesorter

Let’s do these three things with the tablesorter plugin:http://tablesorter.com/. It lets users click on column headers to sort a table.

Adding the plugin

Normally, you would download the plugin to your computer, and then upload it to your server. Some plugins also come with CSS files, images, and other things that you need to upload. Look at the plugin’s documentation to figure out exactly what to do with it.

tablesorter needs just one JS file. For convenience, I’ve put the file on CoreDogs. You can add it to your pages by inserting the following line in the <head> section of each page you want to use it on.

<script type="text/javascript" src="http://coredogs.com/resources/jquery.tablesorter-2.0.3.min.js"></script>

Figure 3. Adding tablesorter

Do this with your live projects, if you want.

Set up your HTML and CSS

tablesorter requires that you:

  • Use <thead> and <tbody> tags in your table.
  • Use <th> tabs inside <thead>.
  • Use <td> tabs inside <tbody>.

Here’s some code for the dog toys table. It doesn’t do any sorting yet – it’s just to get us started.

<table>
  <thead>
    <tr>
      <th>Catalog<br>number</th>
      <th>Name</th>
      <th>Photo</th>
      <th>Average<br>rating</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>243243</td>
      <td>Ball of Chasing</td>
      <td><img src="ball.jpg" alt="Ball of chasing"></td>
      <td>3.9</td>
      <td>4.99</td>
    </tr>
    <tr>
      <td>593922</td>
      <td>Blue Chewey</td>
      <td><img src="blue_chewey.jpg" alt="Blue chewey"></td>
      <td>4.8</td>
      <td>12.99</td>
    </tr>
    <tr>
      <td>293944</td>
      <td>Cookie Bone</td>
      <td><img src="cookie_bone.jpg" alt="Cookie bone"></td>
      <td>3.5</td>
      <td>3.99</td>
    </tr>
    <tr>
      <td>948322</td>
      <td>Cookie Car</td>
      <td><img src="cookie_car.jpg" alt="Cookie car"></td>
      <td>3.6</td>
      <td>3.99</td>
    </tr>
    <tr>
      <td>882030</td>
      <td>Cookie Hydrant</td>
      <td><img src="cookie_hydrant.jpg" alt="Cookie hydrant"></td>
      <td>3.2</td>
      <td>3.99</td>
    </tr>
    <tr>
      <td>323822</td>
      <td>Cookie Shoe</td>
      <td><img src="cookie_shoe.jpg" alt="Cookie shoe"></td>
      <td>4.1</td>
      <td>3.99</td>
    </tr>
    <tr>
      <td>392866</td>
      <td>Rope Twist</td>
      <td><img src="rope.jpg" alt="Rope twist"></td>
      <td>4.3</td>
      <td>11.99</td>
    </tr>
    <tr>
      <td>298882</td>
      <td>Chew Shoes</td>
      <td><img src="shoes.jpg" alt="Chew shoes"></td>
      <td>2.1</td>
      <td>17.95</td>
    </tr>
  </tbody>
</table>

Figure 4. Initial toy code

Everything should be familiar. There’s a head (lines 2 to 10), and a body (lines 11 to 68). The head has one table row. Each column heading uses the <th> tag. The tablesorter plugin needs <th>s so it can identify column headings.

Each row in the body describes a single product. The third column has an image with a thumbnail photo of the product.

The table looks like this so far:

Unstyled table

Figure 5. Unstyled table

We want to add CSS styles to make it look like this:

Styled table

Figure 6. Styled table

We have to make some changes:

Unstyled table changes

Figure 7. Unstyled table changes

The font family, size, and color needs to be changed for all the text. The header needs to have its color flipped around: white text on a dark background. The cells with number values – rating and price – need to be aligned to the right. The cells in the body need a border.

Here’s some code to do the job:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Sorting a table</title>
    <style type="text/css">
      body {
        font-family: Verdana, Helvetica, sans-serif;
        font-size: 12px;
        color: #585858;
      }
      #dog_toys {
        border-spacing: 3px;
      }
      #dog_toys thead th {
        color: white;
        background-color: #683900;
        padding: 4px;
      }
      #dog_toys tbody td {
        border: 1px dotted #683900;
        padding: 2px;
      }
      #dog_toys tbody td.catalog_id {
        text-align: center;
      }
      #dog_toys tbody td.photo {
        text-align: center;
      }
      #dog_toys tbody td.rating {
        text-align: center;
      }
      #dog_toys tbody td.price {
        text-align: right;
      }
    </style>
  </head>
  <body>
    <table id="dog_toys">
      <thead>
        <tr>
          <th>Catalog<br>number</th>
          <th>Name</th>
          <th>Photo</th>
          <th>Average<br>rating</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="catalog_id">243243</td>
          <td class="name">Ball of Chasing</td>
          <td class="photo"><img src="ball.jpg" alt=""></td>
          <td class="rating">3.9</td>
          <td class="price">4.99</td>
        </tr>
        <tr>
          <td class="catalog_id">593922</td>
          <td class="name">Blue Chewey</td>
          <td class="photo"><img src="blue_chewey.jpg" alt="Blue chewey"></td>
          <td class="rating">4.8</td>
          <td class="price">12.99</td>
        </tr>
        <tr>
          <td class="catalog_id">293944</td>
          <td class="name">Cookie Bone</td>
          <td class="photo"><img src="cookie_bone.jpg" alt="Cookie bone"></td>
          <td class="rating">3.5</td>
          <td class="price">3.99</td>
        </tr>
        <tr>
          <td class="catalog_id">948322</td>
          <td class="name">Cookie Car</td>
          <td class="photo"><img src="cookie_car.jpg" alt="Cookie car"></td>
          <td class="rating">3.6</td>
          <td class="price">3.99</td>
        </tr>
        <tr>
          <td class="catalog_id">882030</td>
          <td class="name">Cookie Hydrant</td>
          <td class="photo"><img src="cookie_hydrant.jpg" alt="Cookie hydrant"></td>
          <td class="rating">3.2</td>
          <td class="price">3.99</td>
        </tr>
        <tr>
          <td class="catalog_id">323822</td>
          <td class="name">Cookie Shoe</td>
          <td class="photo"><img src="cookie_shoe.jpg" alt="Cookie shoe"></td>
          <td class="rating">4.1</td>
          <td class="price">3.99</td>
        </tr>
        <tr>
          <td class="catalog_id">392866</td>
          <td class="name">Rope Twist</td>
          <td class="photo"><img src="rope.jpg" alt="Rope twist"></td>
          <td class="rating">4.3</td>
          <td class="price">11.99</td>
        </tr>
        <tr>
          <td class="catalog_id">298882</td>
          <td class="name">Chew Shoes</td>
          <td class="photo"><img src="shoes.jpg" alt="Chew shoes"></td>
          <td class="rating">2.1</td>
          <td class="price">17.95</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

Figure 8. Added styles

The changes in the look are all made by CSS. But I changed the HTML as well. Why? To create things I could hook the CSS rules to.

Changing the HTML

I wanted to make it easy to hook CSS rules to the things that needed to change their look. Here’s what I did.

<table id="dog_toys">
  <thead>
	<tr>
	  <th>Catalog<br>number</th>
	  <th>Name</th>
	  <th>Photo</th>
	  <th>Average<br>rating</th>
	  <th>Price</th>
	</tr>
  </thead>
  <tbody>
	<tr>
	  <td class="catalog_id">243243</td>
	  <td class="name">Ball of Chasing</td>
	  <td class="photo"><img src="ball.jpg" alt="Ball of chasing"></td>
	  <td class="rating">3.9</td>
	  <td class="price">4.99</td>
	</tr>
	<tr>
	  <td class="catalog_id">593922</td>
	  <td class="name">Blue Chewey</td>
	  <td class="photo"><img src="blue_chewey.jpg" alt="Blue chewey"></td>
	  <td class="rating">4.8</td>
	  <td class="price">12.99</td>
	</tr>
...
  </tbody>
</table>

Figure 9. Adding names to the HTML

First, I gave the table an id (line 1). As we will see, this is enough for almost all of the CSS rules I need to make.

But some of the columns needed special treatment. For example, the body’s photo column needs to be centered. And the price needs to be aligned to the right.

The price is right? Ack! Bad pun! Boo!

I gave each column (each <td> tag) a class. Then I could style the classes to get the alignment I wanted (center, right, whatever). You can see this on line 13, 14, and so on.

CC
CC

You gave the table an id on line 1, but on line 13 you gave the <td> a class. Why not give the <td> an id as well? Like <td id="catalog_id">. Wouldn’t that be more consistent?

Renata
Renata

Oo, oo, I know!

Kieran
Kieran

Go ahead, Renata.

Renata
Renata

Because you can only use the same id once per page. If you used <td id="catalog_id"> on line 13, you couldn’t do that again on line 20.

Kieran
Kieran

That’s right! If you give two things the same id, you might get strange results. But you can use the same class as much as you want.

Adding the CSS

Now that I have the names added to the HTML, I can use them in the CSS.

body {
  font-family: Verdana, Helvetica, sans-serif;
  font-size: 12px;
  color: #585858;
}
#dog_toys {
  border-spacing: 3px;
}
#dog_toys thead th {
  color: white;
  background-color: #683900;
  padding: 4px;
}
#dog_toys tbody td {
  border: 1px dotted #683900;
  padding: 2px;
}
#dog_toys tbody td.catalog_id {
  text-align: center;
}
#dog_toys tbody td.photo {
  text-align: center;
}
#dog_toys tbody td.rating {
  text-align: center;
}
#dog_toys tbody td.price {
  text-align: right;
}

Figure 10. The styles

The rule in lines 1 to 5 sets font information for the entire page. The rest of the rules start with #dog_toys, so they apply only to the table. The rule in lines 6 to 8 applies to entire table. The next rule styles the table header, and the one after that styles the cells in the body. The rest of the rules set the classes of the columns.

Renata
Renata

You added a class to the product name column: <td class="name">. But you didn’t use the class in the CSS. Why?

Kieran
Kieran

Good question. Clients often want changes to pages. I added the name class to make future changes to that column easier.

It isn’t strictly necessary. I could have left it out. That would still be OK.

Exercise: More color table styling

Make your color table look like this:

More styles

The text is right aligned in some of the cells. The text color for the numbers matches the name of the color.

There is no striping. It tends to interfere with the sorting you’ll do later.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Calling the plugin

The last step is to call the plugin. Here’s code to add to the <head> of the page.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://coredogs.com/resources/jquery.tablesorter-2.0.3.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){ 
    $("#dog_toys").tablesorter(
      { headers: {
        2: {
            sorter: false
        }
      } 
    } ); 
  }); 
</script>

Figure 11. Calling the plugin

Line 1 gets jQuery from Google. Line 2 gets the tablesorter plugin from CoreDogs. Lines 4 to 12 are executed when the page has been loaded into the browser.

Line 5 is where the real action is. To make the table sortable, all I have to do is this:

$("#dog_toys").tablesorter();

This makes every column in the table sortable. The user only needs to click on the column headings.

The problem is, I don’t want all the columns to be sortable. Sorting on the photo column doesn’t make a lot of sense. So I want the plugin to make that column not sortable.

That’s what lines 6 to 10 do. They set options for the headers (line 6), setting the photo column (line 7) to not sortable (line 8).

Why is there a 2 for the photo column (line 7)? That’s the column’s index. The first column is has an index of 0. The second column has an index of 1. The third column has an index of 2. The photo column is the third column, so I use an index of 2 in line 7.

Working out the syntax – what goes where – is messy. I took the easy way out. I found this in the plugin’s documentation:

For example, to disable sorting on the first two columns of a table: headers: { 0: { sorter: false}, 1: {sorter: false} }

I just copied it, changed the 0 to a 2, and got rid of the other column (the 1). I do this whenever I can – look for an example of what I want to do, copy it, and change it if necessary.

You can try the final page.

Exercise: Sorting the color table

Make your color table sortable, on all columns.

Hint: .tablesorter() is enough.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

On this page, you learned how to make sortable tables using a jQuery plugin.

What now?

You’ll do more table exercises on the next page. Make sure you do them! It’s the only way to learn.

Exercises: A Web page with tables

You should do the five recommended exercises. Do the optional exercises if you want more practice.

Exercises in the Explore section are more challenging. You may need to use HTML and CSS that isn’t covered in CoreDogs. Get ready to Google!

Recommended

Exercise: Money images

Make a page that looks like this:

Money images

You can use these images:

One front

One back

Five front

Five back

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Population growth rate

Create a table showing the population growth rate for countries around the world. It should look like this:

Growth rate

The data comes from the CIA World Fact Book.

There’s lots of data. You can copy from a file with the table already created. It will save you a lot of typing.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Population growth rate with stripes

Add stripes to your population growth rate table:

Growth rate striped

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Sortable population growth rate table

Remove the stripes from your table. Then give users the ability to sort your population growth rate table on any column.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Optional

Exercise: Dog browser - Bs

Create a page that helps people learn about dogs. The page shows four breeds beginning with B. It should use a <table> to show the dogs.

When the page loads, it looks like this:

Opening screen

Figure 1. Opening screen

When the mouse moves over a dog, two things happen:

  • The mouse cursor changes to a hand.
  • The breed’s name shows up.

Mouse over

Figure 2. Mouse over

When the user clicks on a dog, details of the breed show:

Show details after click

Figure 3. Show details after click

All of the text is from Wikipedia.

When the user moves the mouse off the dog that was clicked, the details are hidden. For example, this is what happens if the user moves the mouse from the Bichon Frise to the Basenji:

Mouse moved to another dog

Figure 4. Mouse moved to another dog

Here are the dog images:

Basenji

Bichon Frise

Bloodhound

Borzoi

The following code might save you some typing.

$('#dog_details').text(
  'The Basenji is a breed of hunting dog that was \
   bred from stock originating in central Africa. \
   Most of the major kennel clubs in the English-speaking \
   world place the breed in the Hound Group; \
   more specifically, it may be classified as belonging \
   to the sighthound type.');

$('#dog_details').text(
  'A Bichon Frise (French, meaning "curly white lap dog") \
   is a small breed of dog of the Bichon type. They are \
   popular pets, similar in appearance to, but larger than, \
   the Maltese. They are a non-shedding breed that requires \
   daily grooming. This lack of shedding makes the Bichon \
   Frise a hypoallergenic breed, which is a very good dog \
   for people who have allergies.');

$('#dog_details').text(
  'The Bloodhound (also known as the St. Hubert hound \
   and Sleuth Hound) is a large breed of dog that was \
   bred originally to hunt deer and wild boar, later \
   specifically to track human beings by scent. It is \
   famed for its ability to follow scents hours or \
   even days old over great distances.');
   
$('#dog_details').text(
  'The borzoi is a breed of domestic dog (Canis lupus \
   familiaris) also called the Russian wolfhound and \
   descended from dogs brought to Russia from central \
   Asian countries. It is similar in shape to a greyhound, \
   and is also a member of the sighthound family.');

The \ is JavaScript’s line continuation character. It lets you split a statement across lines. Mainly it’s used to split long strings, to make them easier to read in a code editor, like NetBeans.

Notes:

  • Remember, your page should use a <table> to show the dogs.
  • You can bind both click and hover events to the same element.

Upload your solution to your server, and paste the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Explore

These challenging exercises may use HTML not covered in CoreDogs. Get ready to Google!

Exercise: Sticky headers

Improve your population growth rate table. Make the column headers sticky. As the user scrolls through the page, the column headers (Rank, Country, and Rate) stay in view.

Hint: is there a jQuery plugin you can use?

Upload the solution to your server, and enter the URL.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Exercise: Download table data

Figure out a way you can help the user put the data in the population growth rate table into Excel, or another spreadsheet program.

Hint: find out what CSV means.

Upload the solution to your server, and enter the URL.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?