show/hide html table columns using css

Posted by Art Peterson on Stack Overflow See other posts from Stack Overflow or by Art Peterson
Published on 2010-05-18T14:49:22Z Indexed on 2010/05/18 15:20 UTC
Read the original article Hit count: 274

Filed under:
|
|
|

I want to display a basic html table with controls to toggle showing/hiding of additional columns:

<table id="mytable">
    <tr>
        <th>Column 1</th>
        <th class="col1">1a</th>
        <th class="col1">1b</th>
        <th>Column 2</th>
        <th class="col2">2a</th>
        <th class="col2">2b</th>
    </tr>
    <tr>
        <td>100</td>
        <td class="col1">40</td>
        <td class="col1">60</td>
        <td>200</td>
        <td class="col2">110</td>
        <td class="col2">90</td>
    </tr>
</table>

So Column 1 and Column 2 will be the only columns displayed by default - but when you click on the Column 1 I want 1a and 1b to toggle, and same with Column 2 with 2a and 2b. I may end up with more columns and lots of rows - so any javascript looping approaches have been too slow to work with when I tested.

The only approach that seems to be fast enough is to set up some css like this:

table.hide1 .col1 { display: none; }
table.hide2 .col2 { display: none; }
table.hide3 .col3 { display: none; }

table.show1 .col1 { display: table-cell; }
table.show2 .col2 { display: table-cell; }
table.show3 .col3 { display: table-cell; }

And then set up onClick function calls on the table header cells that will trigger a toggle - and determine which css class to set "mytable" to that will create the toggle effect that I'm looking for. Is there an easy way to set this up so that the code can work for n # of columns?

© Stack Overflow or respective owner

Related posts about css

Related posts about html