January 22nd, 2008

Javascript: show and hide a table cell

Challenge:
You want to show/hide some table cells.

Problem:
To hide a table cell, you set its style display property to "display:none". Easily accomplished. To show it, you set the style display property to either "block" in IE, or "table-cell" in Firefox. There's the challenge - if you set the cell style to "display:block", Firefox will show the cell, but it won't do all the normal resizing behavior that a table cell ought to do. The proper display value for a table <td> in Firefox is "table-cell".

Solution:
One might think that convoluted browser detection would be needed. Not so! The solution is easy, because IE throws an exception when it encounters the 'table-cell' property. We can wrap the code in a try-catch block, and it will only execute the try code if it doesn't produce an error.

elem.style.display="block";
try{elem.style.display="table-cell";}catch(err){}

If IE didn't complain with a thrown exception, this trick wouldn't work and we may have resorted to archaic browser detection methods.

Another way to do the same thing is:

try{
elem.style.display="table-cell";
}catch(err){
elem.style.display="block";
}

Filed under Uncategorized

One Response to “Javascript: show and hide a table cell”

  1. rachel Says:

    awesome! i’ve been working always in FF so i’m finding so many issues now that i’m running my code in IE. thanks for solving one of them!!!

Leave a Reply