jQuery fadeIn() and fadeOut() Methods
You can use the jQuery fadeIn()
and fadeOut()
methods to display or hide the HTML elements by gradually increasing or decreasing their opacity.
<script>
$(document).ready(function(){
// Fading out displayed paragraphs
$(".out-btn").click(function(){
$("p").fadeOut();
});
// Fading in hidden paragraphs
$(".in-btn").click(function(){
$("p").fadeIn();
});
});
</script>
Like other jQuery effects methods, you can optionally specify the duration or speed parameter for the fadeIn()
and fadeOut()
methods to control how long the fading animation will run. Durations can be specified either using one of the predefined string 'slow'
or 'fast'
, or in a number of milliseconds; higher values indicate slower animations.
You can also specify a callback function to be executed after the fadeIn()
or fadeOut()
method completes. We'll learn more about the callback function in upcoming chapters.
<script>
$(document).ready(function(){
// Display alert message after fading out paragraphs
$(".out-btn").click(function(){
$("p").fadeOut("slow", function(){
// Code to be executed
alert("The fade-out effect is completed.");
});
});
// Display alert message after fading in paragraphs
$(".in-btn").click(function(){
$("p").fadeIn("slow", function(){
// Code to be executed
alert("The fade-in effect is completed.");
});
});
});
</script>
fadeToggle()
MethodThe jQuery fadeToggle()
method display or hide the selected elements by animating their opacity in such a way that if the element is initially displayed, it will be fade out; if hidden, it will be fade in (i.e. toggles the fading effect).
<script>
$(document).ready(function(){
// Toggles paragraphs display with fading
$(".toggle-btn").click(function(){
$("p").fadeToggle();
});
});
</script>
Similarly, you can also specify a callback function for the fadeToggle()
method.
<script>
$(document).ready(function(){
// Display alert message after fade toggling paragraphs
$(".toggle-btn").click(function(){
$("p").fadeToggle(1000, function(){
// Code to be executed
alert("The fade-toggle effect is completed.");
});
});
});
</script>
fadeTo()
MethodThe jQuery fadeTo()
method is similar to the .fadeIn()
method, but unlike .fadeIn()
the fadeTo()
method lets you fade in the elements to a certain opacity level.
The required opacity parameter specifies the final opacity of the target elements that can be a number between 0 and 1. The duration or speed parameter is also required for this method that specifies the duration of the fade to animation.
<script>
$(document).ready(function(){
// Fade to paragraphs with different opacity
$(".to-btn").click(function(){
$("p.none").fadeTo("fast", 0);
$("p.partial").fadeTo("slow", 0.5);
$("p.complete").fadeTo(2000, 1);
});
});
</script>