Home > Articles > Open Source > Ajax & JavaScript

Enrich Your HTML Tables with JavaScript Progressive Enhancement

  • Print
  • + Share This
Tabular headaches. Ever had one? Ivan Pepelnjak can relate because he has struggled with table formatting for years. But he has figured out how to use the JavaScript Progressive Enhancement technology to simplify the formatting of web pages and make lively, good-looking HTML tables.
Like this article? We recommend

I’ve been struggling with table formatting for years. Although I could use Cascading Style Sheets (CSS) to automate most of my other formatting/design scenarios, tables remained elusive. For example, the simplest requirements (alternate background on even/odd rows and borders between columns) required manually applying CSS classes to half the rows and at least first or last column

While fixing the server-side scripts to apply the necessary classes to the table rows and cells is usually easy, the tables produced manually remain a huge pain. Just imagine adding a row in the middle of a long table; all the subsequent rows would have to be fixed.

Tabular Headaches

With no obvious short-term CSS advances that would help me solve this problem, I finally gave up and decided to use client-side JavaScript to add the final design touches to the tables. Obviously, the HTML markup itself should produce reasonably acceptable tables with JavaScript progressive enhancement adding the final touches.

To start the project, I defined a new CSS class that would be applied to the whole table and a number of CSS rules that defined the default formatting of cells in the table:

  • The header cells would have gray background and left, right, and bottom borders.
  • All the other table cells would have left and right borders.

Furthermore, I had to define additional classes to be applied with the JavaScript code to enhance the table:

  • The OddRow and EvenRow classes for the table rows
  • The FirstColumn and LastColumn classes for the first and last cell in the row

The resulting CSS rules are included in the following printout and you can view the whole CSS style sheet and the resulting table on my web site.

TABLE.printout { border-collapse: collapse; }

TABLE.printout TD, TABLE.printout TH {
 padding-left:8px; padding-right:8px;
 padding-top: 2pt; padding-bottom: 2pt; 
 border-width: 1px; border-right-style: outset; 
 border-left-style: outset; }
TABLE.printout TH { 
 border-bottom-style: outset; 
 background-color: #C0C0C0; }

TABLE.printout TR.EvenRow { background-color: #E0E0E0; }
TABLE.printout TR.OddRow {}

TABLE.printout .FirstColumn { border-left-style: none; }

TABLE.printout .LastColumn { border-right-style: none; }
  • + Share This
  • 🔖 Save To Your Account