HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery Hide and Show

One of the most popular uses for jQuery is creating simple visual effects. The hide() and show() methods allow you to instantly control the visibility of any element on your page with smooth, professional transitions.


1. The hide() Method

The hide() method sets the CSS display property of an element to none. This removes the element from the layout entirely.

$(selector).hide(speed, callback);

Example: Hiding a paragraph when a button is clicked.

$("#hideBtn").click(function() {
    $("p").hide();
});

2. The show() Method

The show() method restores the element's visibility by resetting the display property (usually to block or inline).

$(selector).show(speed, callback);

3. The toggle() Method

The toggle() method is a powerful shortcut. It checks the current state of an element: if it is shown, it hides it; if it is hidden, it shows it. This saves you from writing complex if...else logic.

$("#toggleBtn").click(function() {
    $("p").toggle();
});

Speed Parameters

Both methods accept a **speed** parameter that controls how long the transition takes. You can use strings or milliseconds:

  • "slow" — A gentle 600ms transition.
  • "fast" — A quick 200ms transition.
  • Milliseconds — A custom time (e.g., 1000 for 1 second).
// Hide with custom speed
$("#target").hide(1000); // Takes 1 second
$("#target").show("slow"); 

Why are these better than CSS?

While you can hide elements with CSS display: none, jQuery's methods are dynamic and include a "sliding and fading" effect that makes the transition look smoother and more polished to the user.

Comparison:
  • CSS: Instant change, no transition, requires manual state tracking.
  • jQuery: Animated transitions, built-in speed control, automatic state tracking with toggle().

Using Callbacks

The **callback** parameter is a function that runs *after* the hide or show effect is completely finished. This is useful for sequencing actions.

$("h1").hide("slow", function() {
    alert("The heading is now gone!");
});
Pro Tip: Only use hide()/show() for logic that needs to be triggered by user events. For static hidden content, stick to plain CSS to avoid "flicker" on page load.

Key Points to Remember

  • hide() and show() manipulate the CSS display property.
  • toggle() is the most efficient way to create open/close menus or accordions.
  • Specifying a speed creates a smooth animation; without it, the change is instant.
  • Use callbacks to trigger code only after an animation finishes.
  • Hidden elements still exist in the DOM; they are just not visible to the user.