jQuery Introduction | Effects | Fade Effects .fadeIn() .fadeOut() .fadeToggle()

Fade effects

In jQuery, a fade effect is represented by quickly changing the CSS opacity value of the element. The methods used to create these fade effects are as follows.

Method Description
.fadeIn() Shows the selected element by gradually increasing its CSS opacity value.
.fadeOut() Hides the selected element by gradually decreasing its CSS opacity value.
.fadeToggle() Alternates between applying the fadeIn() and fadeOut() methods to the selected element.
.fadeTo() Directly sets the opacity value used by the fade effect.

.fadeIn() and .fadeOut() methods - showing and hiding

The .fadeOut() method gradually hides the selected element, and the .fadeIn() method gradually shows it.

$("#btnFadeOut").on("click", function() {
    $("div").fadeOut();
});
$("#btnFadeIn").on("click", function() {
    $("div").fadeIn();
});

In the example above, the <div> element disappears with the .fadeOut() method and is displayed with the .fadeIn() method.

Run code

.hide() and .show() methods - setting effect speed

You can also set the speed of an effect by passing a value in milliseconds(ms) or a keyword such as “slow” or “fast”.

$("#btnFadeOut").on("click", function() {
  $("div").fadeOut(1000);
});
$("#btnFadeIn").on("click", function() {
  $("div").fadeIn("fast");
});

In the example above, the effect speed is set with the .fadeOut(1000) method and the .fadeIn("fast") method.

Run code

.fadeToggle() method - toggling the fade effect

jQuery provides the .fadeToggle() method, which performs a different action depending on the current display state of the selected element.
If the selected element is currently hidden, it performs the behavior of the .fadeIn() method; if it is visible, it performs the behavior of the .fadeOut() method.

$("#btnFadeToggle").on("click", function() {
  $("div").fadeToggle();
});

In the example above, when the element whose id is btnFadeToggle is clicked, the <div> element alternates between being shown and hidden.

Run code

.fadeTo() method - setting fade opacity

With the .fadeTo() method, you can directly set the final opacity value used by the fade effect.

$("button").on("click", function() {
  $("#first").fadeTo(1000, 0.2);
  $("#second").fadeTo(1000, 0.5);
  $("#third").fadeTo(1000, 0.8);
});

In the example above, the elements whose ids are “first”, “second”, and “third” change their opacity values to 0.2, 0.5, and 0.8 respectively over 1 second.

Run code