Showing and Hiding Elements
In this page:
show()
Calling show() instantly reveals an element that currently has display:none, restoring its normal display value. Without a duration argument, the change happens immediately with no animation.
Example: show()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="display:none">Hidden content</div>
<button id="btn">Show</button>
<script>
$("#btn").on("click", function() {
$("#box").show();
});
</script>
</body>
</html>
hide()
hide() sets an element's display to none instantly, removing it from the page's layout entirely -- unlike changing visibility or opacity, hidden elements no longer take up any space.
Example: hide()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Visible content</div>
<button id="btn">Hide</button>
<script>
$("#btn").on("click", function() {
$("#box").hide();
});
</script>
</body>
</html>
toggle()
toggle() checks an element's current visibility and switches it to the opposite state, so the same call shows a hidden element and hides a visible one, which is ideal for buttons that flip a panel open and closed.
Example: toggle()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="panel">Panel content</div>
<button id="btn">Toggle</button>
<script>
$("#btn").on("click", function() {
$("#panel").toggle();
});
</script>
</body>
</html>
Speed
Passing a duration in milliseconds, or a keyword like slow or fast, turns show() and hide() from an instant snap into a smooth animated transition instead.
Example: Speed
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Content</div>
<script>
$("#box").hide("slow");
</script>
</body>
</html>
Click to Toggle
Wiring a button's click handler to call .toggle() on a target element is one of the most common jQuery patterns for building simple show/hide UI like FAQ answers or dropdown menus.
Example: Click to Toggle
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="faqBtn">What is jQuery?</button>
<p id="answer" style="display:none">A JavaScript library.</p>
<script>
$("#faqBtn").on("click", function() {
$("#answer").toggle();
});
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: