Weird bug with hiding columns in IE7

Sometimes when you create a table, you need to dynamically toggle certain columns visibility. I usually use the following approach:

This is a very common scenario and it’s much more efficient than the approach where you go through all the elements in javascript and toggle their personal display mode.

There’s also an inverted approach where by default elements are hidden and assigned class specifies positive display – table-cell for CSS2.1-compliant browsers and block for IE6. But my approach is better as it’s cleaner – there’s no need for IE6-specific code (usually assigned by star hack).

However, in IE7 with both of the approaches the cells’ display is not switched as you may notice by viewing the testcase.

But as in most cases, there’s a workaround – you have to “poke” any TH of your table. In this testcase I added the following code:

/*@cc_on if (!document.querySelector)
    document.getElementsByTagName('th')[0].className = 'wt2';
@*/

to the toggling function. As you may know, js code within /*@cc_on ... @*/ block will be executed only by IE, and only IE8 has support for document.querySelector interface, so chances are that this code will be executed only in IE with version earlier than 8, which is precisely what we need (as IE8 doesn't have this problem).

It’s interesting to know, that YUI Team in their DataTable control in order to implement hiding/showing functionality choosed to loop through all the cells and set their display individually (see hideColumn/showColumn functions here). I understand that this is the bulletproof approach ready to use in any environment, but it can be rather ineffective when your table has a significant amount of rows as it will have to go through all the TR’s. And it will do the loop twice if you choose to hide two columns :) Of course, using my approach requires setting classes for those cells that you were going to hide, so it’s not that flexible, but in the controlled environment it’s definitely the best option.

comments powered by Disqus