From jQuery JavaScript Library
« Back to Effects
toggle( )
Toggle displaying each of the set of matched elements.
If they are shown, toggle makes them hidden (using the
hide method). If they are hidden, toggle makes them shown (using the
show method).
Examples:| Name | Type |
Toggles all paragraphs.
$("button").click(function () {
$("p").toggle();
});
toggle( switch )
Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements).
If the switch is true, toggle makes them hidden (using the
hide method). If the switch is false, toggle makes them shown (using the
show method).
Arguments:| switch | Boolean | |
|---|
| A switch to toggle the display on. |
Examples:| Name | Type |
Shows all paragraphs, then hides them all, back and forth.
var flip = 0;
$("button").click(function () {
$("p").toggle( flip++ % 2 == 0 );
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
var flip = 0;
$("button").click(function () {
$("p").toggle( flip++ % 2 == 0 );
});
});
</script>
</head>
<body>
<button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
</body>
</html>
toggle( speed, [callback] )
Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion.
The height, width, and opacity of each of the matched elements are changed dynamically according to the specified speed. As of jQuery 1.3 the padding and margin are also animated, creating a smoother effect.
Arguments:| speed | String, Number | |
|---|
| A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). |
| callback (Optional) | Function | |
|---|
A function to be executed whenever the animation completes, executes once for each element animated against.
function callback() {
this; // dom element
}
|
Examples:| Name | Type |
Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds.
$("button").click(function () {
$("p").toggle("slow");
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("button").click(function () {
$("p").toggle("slow");
});
});
</script>
<style>
p { background:#dad;
font-weight:bold;
font-size:16px; }
</style>
</head>
<body>
<button>Toggle 'em</button>
<p>Hiya</p>
<p>Such interesting text, eh?</p>
</body>
</html>