- by Joel
- 02/07/2008
- CSS, HTML, JavaScript
- 0 comments
I've been working on some code that gets a bunch of data from the server (via XHR) and then builds a big table to display it all. The table is customizable and users can choose which columns they want to show/hide. The only problem is that whenever they show or hide a column we have to recreate the entire table (in Javascript with string concatenation) which is slow. Really slow. I've been thinking about ways around that and I've finally got one that works.
In HTML we have TRs, which let us address individual table rows, but not TCs, so we can't easily identify a table column and modify it. To get around this we can artificially group the TD/TH elements that belong in a column using a CSS class. So, for example, our table could look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<table id="table" class=""> <thead> <tr> <th class="c1">Column 1</th> <th class="c2">Column 2</th> <th class="c3">Column 3</th> <th class="c4">Column 4</th> <th class="c5">Column 5</th> <th class="c6">Column 6</th> </tr> </thead> <tbody> <tr> <td class="c1">Row1 Col1</td> <td class="c2">Row1 Col2</td> <td class="c3">Row1 Col3</td> <td class="c4">Row1 Col4</td> <td class="c5">Row1 Col5</td> <td class="c6">Row1 Col6</td> </tr> </tbody> </table> |
where the c1 through c6 classes are used to identify our columns. Now that we have a way of identifying a column we can use CSS to toggle it's visibility. We'll define a rule that says a TD or a TH that has the same class as the TABLE element should be hidden, like this:
1 2 3 4 5 6 7 8 9 10 11 |
<style type="text/css">
table.c1 th.c1, table.c1 td.c1,
table.c2 th.c2, table.c2 td.c2,
table.c3 th.c3, table.c3 td.c3,
table.c4 th.c4, table.c4 td.c4,
table.c5 th.c5, table.c5 td.c5,
table.c6 th.c6, table.c6 td.c6 {
display: none;
}
</style>
|
When the table doesn't have any of the classes applied the TD or TH elements get the default display value and are visible. However, if we want to hide column three all we have to do is add the "c3" class to the TABLE element and column three will be hidden. While it might seem a little unintuitive that we add the column class to our table to remove the column, we do that because then we can use 'display: none' instead of defining what the visible display state should be. And why does that matter? Because there are sixteen visible display states and only one hidden state and this way we can let the browser figure out what the right visible display states for TD/TH elements are.
To see this concept in action you can take a look at this simple page I threw together.