May 22 2006

Expand/Collapse Blocks Using CSS Display Property

Published by Mike Munhall at 9:53 pm under JavaScript, Web Development

Having to write code to different browsers and platforms is a pain in the arse. I am constantly finding myself having to write alternative versions of some JavaScript function to work with either Inetrnet Exploder or Netscrape. In some cases I have even written different versions of a function for the same browser on different platforms.

One particular problem we (the developers at CRS, my employer) have been struggling with is dynamically showing or hiding a block of HTML inside of either a <div> tag or a table row. Since our application is used primarily by PC users running Internet Explorer, we had been using something like this to dynamically expand and collapse blocks:

collapseexpande_bad.gif
[Download Snippet]

This works in Internet Explorer, but behaves strangely in most other browsers. I won’t get into the details of how each browser handles the code. What we want is a solution that works with all browsers. Right?

Right. I’m embarrassed that I dragged my feet for so long to fix this, writing stupid workarounds for browsers other than PC-IE. The problem in the code snippet above is not the JavaScript, but the block value used for the display property. For a block to expand and render properly, the value of the property should be set to an empty string in the JavaScript and in the HTML. Also, notice the difference in the style attribute of the div tag. The value of the display property is an empty string there as well, without quotes. Qualifying property values in inline styles is common but incorrect and will cause problems.

collapseexpande_ok.gif
[Download Snippet]

Trackback URI | Comments RSS

Leave a Reply