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:
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:
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:


  1. Unfortunately, this does not work if the display: none is set in css instead of inline. Probably because prototype uses display = '', see for an explanation.

  2. You are correct. I didn't mention it since I've gotten used to doing inline "display: none" when I want to show/hide an element with Prototype.

  3. I am using this with A href

    href="/audits" id="isAuditShow">Audits


    href="/audits" id="isAuditShow" style="display: none;">Audits

    and code is

    $('isAuditShow').show(); and

    But it seems it is not working, please help me if you have any comments


// //]]>