jQuery Effect fadeOut() Method



The fade-out effect is a visual transition where an element gradually becomes hidden or transparent from being visible. It smoothly decreases the opacity of the element over a specified duration, creating a smooth transition.

The fadeOut() method is used in jQuery to gradually reduce the opacity of selected elements, simply hiding them by fading them out. It provides a smooth visual transition effect, making elements disappear gradually.

This method can also be used together with "fadeIn()" method.

Syntax

Following is the syntax of fadeOut() method in jQuery −

$(selector).fadeOut(speed,easing,callback)

Parameters

This method accepts the following optional parameters −

  • speed (optional): Specifies the duration of the fade-out animation in milliseconds (default is 400).

  • easing (optional): Specifies the easing function to use for the animation (default is 'swing').

  • callback (optional): A callback function to be executed after the fade-out animation.

Example 1

In the following example, we are fading out a single <div> element with the id "content" using the fadeOut() method −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("#fadeBtn").click(function(){
    $("#content").fadeOut();
  });
});
</script>
</head>
<body>

<div id="content" style="background-color: lightblue; padding: 20px;">
  <h2>This content will fade out.</h2>
</div>
<button id="fadeBtn">Click me!</button>
</body>
</html>

If we click on the button, the <div> element will fade out.

Example 2

In this example, we are fading out multiple <div> elements with the class "fade" −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("#fadeBtn").click(function(){
    $(".fade").fadeOut();
  });
});
</script>
</head>
<body>

<div class="fade" style="background-color: lightblue; padding: 20px;">
  <h2>Element 1</h2>
</div>
<div class="fade" style="background-color: lightcoral; padding: 20px;">
  <h2>Element 2</h2>
</div>
<button id="fadeBtn">Fade Out Elements</button>
</body>
</html>

When a button is clicked, all the three <div> elements will be faded out.

Example 3

In this example, the fade-out animation duration is set to 2000 milliseconds (2 seconds) by passing the duration parameter to the fadeOut() method −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("#fadeBtn").click(function(){
    $("#content").fadeOut(2000); // Duration set to 2000 milliseconds (2 seconds)
  });
});
</script>
</head>
<body>

<div id="content" style="background-color: lightblue; padding: 20px;">
  <h2>This is a content to fade out.</h2>
</div>
<button id="fadeBtn">Click me!</button>
</body>
</html>

When a button is clicked, the <div> element will be fade out in 2 seconds.

jquery_ref_effects.htm
Advertisements