jQuery fadeTo()
The jQuery fadeTo() method is used to fade an element to a specified
opacity (value between 0 and 1).
Unlike fadeIn() and fadeOut(), it allows you to adjust the opacity to any
level, rather than fully showing or hiding the element.
Syntax
$(selector).fadeTo(speed, opacity, easing, callback);
- speed (required): Specifies the duration of the effect. It can be slow, fast, or a number of milliseconds (e.g., 400).
- opacity (required): A value between 0 (fully transparent) and 1 (fully opaque) that specifies the final opacity of the element.
- easing (optional): Specifies the easing function for the transition. Default is swing, and another option is linear.
- callback (optional): A function to be executed once the fadeTo() effect is complete.
<!DOCTYPE html>
<html>
<head>
<title>jQuery fadeTo()
Example</title>
<style>
#box {
width: 200px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<button id="fadeButton">Fade to 50% Opacity</button>
<div id="box"></div>
<script>
$(document).ready(function() {
$("#fadeButton").click(function() {
$("#box").fadeTo(1000, 0.5,
'swing', function() {
console.log("Fade
to 50% opacity complete!");
});
});
});
</script>
</body>
</html>