class method Element.toggle
Element.toggle(element[, bool]) → Element
-
bool
(Boolean
) – Whether the element should be shown or hidden. If not a boolean, this argument will be ignored.
Toggles the CSS display
of element
. Returns element
.
Switches an element's CSS display
between none
and its inherited
value (usually block
or inline
).
By default, toggle
will switch the display to the opposite of its
current state, but will use the bool
argument instead if it's
provided (true
to show the element, false
to hide it).
If the bool
argument is not a boolean, it will be ignored. This
preserves the ability to toggle elements through comparisons (e.g.,
errorElement.toggle(errors > 0)
) while also letting a user do
someElements.each(Element.toggle)
without falling victim to
JavaScript's famous problems with variadic arguments.
Examples
<div id="welcome-message">Welcome</div>
<div id="error-message" style="display:none;">Error</div>
$('welcome-message').toggle();
// -> Element (and hides div#welcome-message)
$('error-message').toggle();
// -> Element (and displays div#error-message)
$('error-message').toggle(true);
// -> Element (and displays div#error-message, no matter what its
// previous state)
Toggle multiple elements using Enumerable#each
:
['error-message', 'welcome-message'].each(Element.toggle);
// -> ['error-message', 'welcome-message']
Toggle multiple elements using Enumerable#invoke
:
$('error-message', 'welcome-message').invoke('toggle');
// -> [Element, Element]
$('error-message', 'welcome-message').invoke('toggle', false);
// -> [Element, Element] (and hides both elements, no matter what
their previous state)
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(); // WON'T WORK!
// -> Element (div#hidden-by-css is still hidden!)
This method can be called either as an instance method or as a generic method. If calling as a generic, pass the instance in as the first argument.