How to Use jQuery fadeIn() to Show Hidden Elements

This article explains how to use the jQuery fadeIn() method to smoothly reveal hidden elements on a web page. You will learn the core syntax, how to configure transition speeds, and how to execute callback functions once the animation completes.

Basic Syntax

The fadeIn() method changes the opacity of selected elements from hidden to fully visible by adjusting their CSS display and opacity properties.

$(selector).fadeIn(speed, easing, callback);
  • speed (optional): Specifies the duration of the effect. Can be predefined strings like "slow" or "fast", or a number in milliseconds (e.g., 1000 for 1 second). The default is 400 milliseconds.
  • easing (optional): Controls the animation speed curve. Default values are "swing" and "linear".
  • callback (optional): A function to execute after the animation completes.

Step-by-Step Implementation

To fade in an element, it must initially be hidden, typically using CSS display: none;.

1. HTML and CSS Setup

<button id="showBtn">Reveal Content</button>

<div id="targetElement" style="display: none; padding: 20px; background-color: #f0f0f0;">
    This content was hidden and is now visible.
</div>

2. The jQuery Script

Attach a click event listener to the button to trigger the fadeIn() method on the hidden element:

$(document).ready(function() {
    $("#showBtn").click(function() {
        $("#targetElement").fadeIn();
    });
});

Controlling Duration

You can customize how fast or slow the element appears by passing a duration parameter:

// Fade in quickly (200 milliseconds)
$("#targetElement").fadeIn("fast");

// Fade in slowly (600 milliseconds)
$("#targetElement").fadeIn("slow");

// Fade in with a custom duration (2 seconds)
$("#targetElement").fadeIn(2000);

Using a Callback Function

If you need to perform an action immediately after the element has finished fading in, pass a function as the final argument:

$("#targetElement").fadeIn(1000, function() {
    console.log("The element is now fully visible.");
});