Search

Thursday, July 19, 2007

Prototype.js Show/Hide Element Gotcha

I like using Prototype.js since it's been around for a while and I already know most of it's methods. I mean to experiment with jQuery but have not gotten around it yet (a disclaimer for anybody meaning to flame me about using something else such as jQuery, mooTools or whatever else). Anyway, a consistent gotcha for me is showing hidden elements after a certain action on the page. Lets take for example my statusContainer from the Gmail Style Ajax Status Message post. I want the div to be hidden when the page loads. My two choices are: 1. Hide the div with JavaScript after the page has been loaded. With Prototype.js, I simply do:
$('statusContainer').hide();
or 2. Set the visibility style of the element to hidden:
<div style="visibility: hidden;" id="statusContainer"></div>
I don't really like the first method since I shouldn't need JavaScript to have the element hidden at first. That leaves me with the second choice. The gotcha is that when you try to use Prototype.js to show the element later with:
$('statusContainer').show();
nothing happens. Why not? Doh! I keep forgetting that internally Prototype.js (at least v1.5.1_rc2 and v1.5.1.1) uses the display style property instead of visibility. So the above second option should say:
<div style="display: none;" id="statusContainer"></div>
With that change, using Prototype.js works fine:
$('statusContainer').show();
// //]]>