Toggle
Flip between hidden and shown with one method.
Syntax
$(selector).toggle(speed);.toggle() shows an element if it is hidden, and hides it if it is shown. Perfect for one-button open/close panels.
Example
Loading editor…
Press Run to see the result.
When to use it
- A sidebar panel opens and closes with one button using .toggle() instead of tracking state manually.
- A read-more link expands and collapses a long paragraph with .toggle() on the hidden portion.
- A mobile menu icon toggles the nav drawer visible/hidden with each tap via .toggle().
More examples
Basic toggle on button click
.toggle() switches the element between visible and hidden on each successive click.
<button id="toggleBtn">Toggle panel</button>
<div id="panel" style="padding:16px;background:#eef;">Panel content</div>
<script>
$(function () {
$("#toggleBtn").click(function () {
$("#panel").toggle();
});
});
</script>Animated toggle with speed
Passing "slow" (or "fast") adds a 600 ms (or 200 ms) animation to the toggle transition.
<button id="t2">Toggle (slow)</button>
<p id="text">This text slides in and out.</p>
<script>
$(function () {
$("#t2").click(function () {
$("#text").toggle("slow");
});
});
</script>Toggle based on a condition
toggle(boolean) shows when true and hides when false, driven here by the checkbox state.
<input id="showExtra" type="checkbox" /> Show extra options
<div id="extra" style="display:none;margin-top:8px;">
<label><input type="text" placeholder="Extra option" /></label>
</div>
<script>
$(function () {
$("#showExtra").on("change", function () {
$("#extra").toggle($(this).is(":checked"));
});
});
</script>
Discussion