Toggling visibility with JQuery
There is a subtle issue with the JQuery toggle method. I had a page that had a div set up similar to this
<div id="divGoodbye" style="border: 1px solid green; visibility: hidden; float: right;">Goodbye</div>
I was trying to toggle it from not visible to visible by doing this
function toggleGoodbye() {
$("#divGoodbye").toggle();
}
It didn’t work; however, if the div was initially styled with visibility:visible it worked perfectly. So I logged a bug report and the JQuery team got back to me with this
In jQuery, visibility is defined as taking up no space in the document.
Most commonly that would be via {{{display:none}}} or {{{width:0}}}. There
are other ways that an element might not be visible in the browser's
viewport, including {{{visibility:hidden}}}, {{{opacity:0}}}, {{{margin-
left:-10000px}}}, or being completely obscured by other elements higher in
the {{{z-index}}} order. Those do not count as hidden as far as jQuery is
concerned.
If you need to use the {{{visibility}}} (or {{{opacity}}}) attribute as
your method of making an element invisible, just track and toggle it
yourself.In jQuery, visibility is defined as taking up no space in the document.
Most commonly that would be via {{{display:none}}} or {{{width:0}}}. There
are other ways that an element might not be visible in the browser's
viewport, including {{{visibility:hidden}}}, {{{opacity:0}}}, {{{margin-
left:-10000px}}}, or being completely obscured by other elements higher in
the {{{z-index}}} order. Those do not count as hidden as far as jQuery is
concerned.
If you need to use the {{{visibility}}} (or {{{opacity}}}) attribute as
your method of making an element invisible, just track and toggle it
yourself.
So I changed the style to this
<div id="divHello" style="border: 1px solid red; display:none; float:left;">
Hello
</div>
This works every time as expected. Hopefully this will save someone a bit of frustration. All scenarios worked in IE7, Firefox and Safari.