In this tutorial, we will discuss fadeTo() method, which is used to adjust the opacity of html elements.
jQuery fadeTo() Method Syntax
$(selector).fadeTo(speed, opacity, callback_function);
$(selector) is any jQuery Selector, which is used to select the html elements on which this effect is being applied.
speed is a required parameter in fadeTo() method, it can take values in milliseconds or string values like “slow” or “fast”.
opacity is the required parameter that can take values between 0 and 1, 0 means completely invisible while 1 means completely visible. The values can be passed in decimal points such as 0.5, 0.25 etc.
callback_function is an optional parameter which defines a function that executes when the effect is complete.
jQuery fadeTo() Example
In the following example, we have adjusted the opacity of different html elements with different values using fadeTo() method. Highest opacity value is 1 (completely visible) and lowest opacity value is 0 (completely invisible). As you can see in the output screenshots that higher opacity element is more visible than lower opacity element.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").fadeTo("slow", 0.25); $("h2").fadeTo("slow", 0.10); $("button").fadeTo("fast", 0.80); }); }); </script> </head> <body> <h2>jQuery fadeTo effect example</h2> <p>This tutorial is published on beginnersbook.com. We have adjusted the opacity of different html elements on this page in the script part, lets see how they look after the button click event.</p> <button>FadeTo</button> </body> </html>
Output:
Before fadeTo button is clicked:
After fadeTo button is clicked:
As you can see that the h2 element has the lowest visibility because we have set the lower opacity value for h2 element and the button has the highest visibility due to the high opacity value set using fadeTo() method.
jQuery fadeTo() Example with speed and callback function.
We can pass the callback function as a parameter in the fadeTo() method. Here we have taken the same example that we have seen above, we have just changed the script part. We have set an alert using callback function that executes once the fade to effect is complete.
$(document).ready(function(){ $("button").click(function(){ $("p") .fadeTo("slow", 0.25, function(){ alert("The paragraph opacity has been adjusted."); }); }); });
Output:
Leave a Reply