Episode 21 of 24
Hide and Show Elements
Learn the simplest jQuery visibility methods — hide, show, and toggle.
The .hide(), .show(), and .toggle() methods are the simplest way to control element visibility.
hide()
$(".box").hide(); // Instant
$(".box").hide("slow"); // Animated
$(".box").hide(500); // 500ms animation
$(".box").hide(300, function() {
console.log("Hidden!");
});
show()
$(".box").show(); // Instant
$(".box").show("fast"); // Animated
$(".box").show(500); // 500ms animation
toggle()
// Toggles between hide and show
$("button").click(function() {
$(".content").toggle(300);
});
// Toggle with callback
$(".panel").toggle(400, function() {
let isVisible = $(this).is(":visible");
console.log("Panel is", isVisible ? "visible" : "hidden");
});
How hide() Works
.hide() sets display: none and remembers the original display value. .show() restores it:
// An inline element
$("span").hide(); // Sets display: none
$("span").show(); // Restores display: inline
// A block element
$("div").hide(); // Sets display: none
$("div").show(); // Restores display: block
Practical Examples
// FAQ accordion
$(".faq-answer").hide();
$(".faq-question").click(function() {
$(".faq-answer").hide(200);
$(this).next(".faq-answer").toggle(200);
});
// Show/hide password
$(".toggle-pw").click(function() {
let $input = $(this).prev("input");
let type = $input.attr("type") === "password" ? "text" : "password";
$input.attr("type", type);
$(this).text(type === "password" ? "Show" : "Hide");
});