5 min read

Advanced Row Striping

Row striping can be as simple as two lines of code to alternate the background color:

$(document).ready(function() {

  $(‘table.sortable tbody tr:odd’).addClass(‘odd’);

  $(‘table.sortable tbody tr:even’).addClass(‘even’);

});

If we declare background colors for the odd and even classes as follows, we can see the rows in alternating shades of gray:

tr.even {

  background-color: #eee;

}

tr.odd {

  background-color: #ddd;

}

While this code works fine for simple table structures, if we introduce non‑standard rows into the table, such as sub-headings, the basic odd-even pattern no longer suffices. For example, suppose we have a table of news items grouped by year, with columns for date, headline, author, and topic. One way to express this information is to wrap each year’s news items in a element and use colspan=”4″> for the subheading. Such a table’s HTML (in abridged form) would look like this:









































































DateHeadlineAuthorTopic
2007
Mar 11SXSWi jQuery MeetupJohn Resigconference
Feb 28 jQuery 1.1.2John Resigrelease
Feb 21jQuery is OpenAjax CompliantJohn Resigstandards
Feb 20jQuery and Jack Slocum's ExtJohn Resigthird-party
2006
Dec 27The Path to 1.1John Resigsource
Dec 18Meet The People Behind jQueryJohn Resigannouncement
Dec 13Helping you understand jQueryJohn Resigtutorial
2005
Dec 17JSON and RSSJohn Resigmiscellaneous

With separate CSS styles applied to

elements within and , a snippet of the table might look like this:

Learning jQuery 1.3

To ensure that the alternating gray rows do not override the color of the subheading rows, we need to adjust the selector expression:

$(document).ready(function() {
$('table.striped tbody tr:not([th]):odd').addClass('odd');
$('table.striped tbody tr:not([th]):even').addClass('even');
});

The added selector, :not([th]), removes any table row that contains a

from the matched set of elements. Now the table will look like this:

Learning jQuery 1.3

Three-color Alternating Pattern

There may be times when we want to apply more complex striping. For example, we can apply a pattern of three alternating row colors rather than just two. To do so, we first need to define another CSS rule for the third row. We’ll also reuse the odd and even styles for the other two, but add more appropriate class names for them:

tr.even,
tr.first {
background-color: #eee;
}
tr.odd,
tr.second {
background-color: #ddd;
}
tr.third {
background-color: #ccc;
}

To apply this pattern, we start the same way as the previous example—by selecting all rows that are descendants of a

, but filtering out the rows that contain a .each() method so that we can use its built-in index:
$(document).ready(function() {
$('table.striped tbody tr').not('[th]').each(function(index) {
//Code to be applied to each element in the matched set.
});
});

To make use of the index, we can assign our three classes to a numeric key: 0, 1, or 2. We’ll do this by creating an object, or map:

$(document).ready(function() {
var classNames = {
0: 'first',
1: 'second',
2: 'third'
};
$('table.striped tbody tr').not('[th]').each(function(index) {
// Code to be applied to each element in the matched set.
});
});

Finally, we need to add the class that corresponds to those three numbers, sequentially, and then repeat the sequence. The modulus operator, designated by a %, is especially convenient for such calculations. A modulus returns the remainder of one number divided by another. This modulus, or remainder value, will always range between 0 and one less than the dividend. Using 3 as an example, we can see this pattern:

3/3 = 1, remainder 0.
4/3 = 1, remainder 1.
5/3 = 1, remainder 2.
6/3 = 2, remainder 0.
7/3 = 2, remainder 1.
8/3 = 3, remainder 2.

And so on. Since we want the remainder range to be 0 – 2, we can use 3 as the divisor (second number) and the value of index as the dividend (first number). Now we simply put that calculation in square brackets after classNames to retrieve the corresponding class from the object variable as the .each() method steps through the matched set of rows:

$(document).ready(function() {
var classNames = {
0: 'first',
1: 'second',
2: 'third'
};
$('table.striped tbody tr').not('[th]').each(function(index) {
$(this).addClass(classNames[index % 3]);
});
});

With this code in place, we now have the table striped with three alternating background colors:

Learning jQuery 1.3

We could of course extend this pattern to four, five, six, or more background colors by adding key-value pairs to the object variable and increasing the value of the divisor in classNames[index % n].


Subscribe to the weekly Packt Hub newsletter. We'll send you the results of our AI Now Survey, featuring data and insights from across the tech landscape.

* indicates required

LEAVE A REPLY

Please enter your comment!
Please enter your name here