toggle

toggle(element) -> HTMLElement

Toggles the visibility of element.

Examples


<div id="welcome-message"></div>
<div id="error-message" style="display:none;"></div>

$('welcome-message').toggle();
// -> HTMLElement (and hides div#welcome-message)

$('error-message').toggle();
// -> HTMLElement (and displays div#error-message)

Notes

Element.toggle cannot display elements hidden via CSS stylesheets. Note that this is not a Prototype limitation but a consequence of how the CSS display property works.


<style>
  #hidden-by-css {
    display: none;
  }
</style>

[…]

<div id="hidden-by-css"></div>

$('hidden-by-css').toggle(); // WONT' WORK!
// -> HTMLElement (div#hidden-by-css is still hidden!)

Backwards compatibility change

In previous versions of Prototype, you could pass an arbitrary number of elements to Element.toggle, Element.show, and Element.hide, for consistency, this is no longer possible in version 1.5!

You can however achieve a similar result by using Enumerables:


['error-message', 'welcome-message'].each(Element.toggle);
// -> ['error-message', 'welcome-message'] 
// and toggles the visibility of div#error-message and div#confirmation-message.

or even better:


$('error-message', 'welcome-message').invoke('toggle');
// -> [HTMLElement, HTMLElement] (div#error-message and div#welcome-message)
// and toggles the visibility of div#error-message and div#confirmation-message.