Hide and Show
Make elements disappear and reappear, instantly or with animation.
Syntax
$(selector).hide(speed); $(selector).show(speed);.hide() and .show() change an element's visibility. With no argument they are instant; with a duration they animate.
$("#box").hide(); // instant
$("#box").show(400); // fades and grows over 400msDurations can be a number of milliseconds, or the words "slow" and "fast".
Example
Loading editor…
Press Run to see the result.
When to use it
- A FAQ page hides all answer panels on load and shows each one when its question heading is clicked.
- A cookie banner shows itself on first visit and hides when the user clicks Accept.
- An admin panel shows a loading spinner with .show() before an AJAX call and hides it with .hide() on completion.
More examples
Instant hide and show on click
.hide() sets display:none instantly; .show() restores the element to its previous display value.
<button id="hBtn">Hide</button>
<button id="sBtn">Show</button>
<div id="box" style="padding:20px;background:#ddf;">Content box</div>
<script>
$(function () {
$("#hBtn").click(function () { $("#box").hide(); });
$("#sBtn").click(function () { $("#box").show(); });
});
</script>Slow animated hide with duration
Passing a millisecond value to .hide() animates opacity and height together over that duration.
<button id="animHide">Hide slowly</button>
<p id="para">This paragraph will disappear.</p>
<script>
$(function () {
$("#animHide").click(function () {
$("#para").hide(800);
});
});
</script>Show a spinner during AJAX load
.show() reveals the spinner before the request and .hide() removes it once the response arrives.
<button id="load">Load data</button>
<div id="spinner" style="display:none;">Loading...</div>
<div id="data"></div>
<script>
$(function () {
$("#load").click(function () {
$("#spinner").show();
$.get("/api/data", function (res) {
$("#spinner").hide();
$("#data").text(JSON.stringify(res));
});
});
});
</script>
Discussion