jQuery fadeTo()

The opacity to which the selected element should fade out of visibility can also be controlled in jQuery.

The fadeTo() method allows the fading of an element to a desired opacity.

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeTo("fast",0.15);
});
});
</script>
</head>
<body>
<p>Click to fade me out upto 0.15 opacity.</p>
<button>Fade To</button><br><br>
<div id="div1" style="width:100px;height:100px;background-color:red;"></div>
</body>
</html>

Passing speed and opacity parameters are mandatory while using fadeTo() method. There are also some optional parameters that can be passed along with these two parameters.

Syntax:

$(selector).fadeTo(speed,opacity,callback);

Speed:

  • Speed is the required parameter to be passed as an argument in the fadeTo() method.
  • Speed specifies the duration of the effect (time taken to fade the element out of the visibility to the desired opacity level).
  • Speed parameters can take values as “fast”, “slow” or values in milliseconds.

Opacity:

  • The opacity parameter is a required parameter that specifies fading to a given opacity level.
  • The opacity value can range between 0 and 1.

Callback:

  • The callback is an optional function that is often passed as an argument in the fadeTo()method.

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeTo("slow", 0.25);
$("#div2").fadeTo("fast", 0.10);
$("#div3").fadeTo("2000", 0.09);
});
});
</script>
</head>
<body>
<p>Click to fade us out upto desired opacity.</p>
<button>Fade To</button><br><br>
<div id="div1" style="width:40px;height:80px;background-color:red;border-radius:20px"></div><br>
<div id="div2" style="width:40px;height:80px;background-color:yellow;border-radius:20px;"></div><br>
<div id="div3" style="width:40px;height:80px;background-color:green;border-radius:20px"></div>
</body>
</html>