jQuery Table Manipulation: Part 2

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 <tbody> element and use <th colspan=”4″> for the subheading. Such a table’s HTML (in abridged form) would look like this:

<table class="striped">
<thead>
<tr>
<th>Date</th>
<th>Headline</th>
<th>Author</th>
<th class="filter-column">Topic</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4">2007</th>
</tr>
<tr>
<td>Mar 11</td>
<td>SXSWi jQuery Meetup</td>
<td>John Resig</td>
<td>conference</td>
</tr>
<tr>
<td>Feb 28</td>
<td>jQuery 1.1.2</td>
<td>John Resig</td>
<td>release</td>
</tr>
<tr>
<td>Feb 21</td>
<td>jQuery is OpenAjax Compliant</td>
<td>John Resig</td>
<td>standards</td>
</tr>
<tr>
<td>Feb 20</td>
<td>jQuery and Jack Slocum's Ext</td>
<td>John Resig</td>
<td>third-party</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4">2006</th>
</tr>
<tr>
<td>Dec 27</td>
<td>The Path to 1.1</td>
<td>John Resig</td>
<td>source</td>
</tr>
<tr>
<td>Dec 18</td>
<td>Meet The People Behind jQuery</td>
<td>John Resig</td>
<td>announcement</td>
</tr>
<tr>
<td>Dec 13</td>
<td>Helping you understand jQuery</td>
<td>John Resig</td>
<td>tutorial</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4">2005</th>
</tr>
<tr>
<td>Dec 17</td>
<td>JSON and RSS</td>
<td>John Resig</td>
<td>miscellaneous</td>
</tr>
</tbody>
</table>

With separate CSS styles applied to <th> elements within <thead> and <tbody>, a snippet of the table might look like this:

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 <th> from the matched set of elements. Now the table will look like this:

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 <tbody>, but filtering out the rows that contain a <th<. This time, however, we attach the .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:

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].

Packt

Share
Published by
Packt

Recent Posts

Top life hacks for prepping for your IT certification exam

I remember deciding to pursue my first IT certification, the CompTIA A+. I had signed…

3 years ago

Learn Transformers for Natural Language Processing with Denis Rothman

Key takeaways The transformer architecture has proved to be revolutionary in outperforming the classical RNN…

3 years ago

Learning Essential Linux Commands for Navigating the Shell Effectively

Once we learn how to deploy an Ubuntu server, how to manage users, and how…

3 years ago

Clean Coding in Python with Mariano Anaya

Key-takeaways:   Clean code isn’t just a nice thing to have or a luxury in software projects; it's a necessity. If we…

3 years ago

Exploring Forms in Angular – types, benefits and differences   

While developing a web application, or setting dynamic pages and meta tags we need to deal with…

3 years ago

Gain Practical Expertise with the Latest Edition of Software Architecture with C# 9 and .NET 5

Software architecture is one of the most discussed topics in the software industry today, and…

3 years ago