About Lesson
Fading Elements in jQuery
In this lesson, you will learn how to create smooth fading effects for elements using jQuery. The fading methods allow you to add visual transitions to your web page elements.
1. .fadeIn() Method
The .fadeIn()
method gradually makes an element visible by increasing its opacity.
JavaScript
$("#fade-in").click(function () {
$("#box").fadeIn();
});
2. .fadeOut() Method
The .fadeOut()
method gradually hides an element by decreasing its opacity.
JavaScript
$("#fade-out").click(function () {
$("#box").fadeOut();
});
3. .fadeToggle() Method
The .fadeToggle()
method toggles between fading in and fading out the selected element.
JavaScript
$("#fade-toggle").click(function () {
$("#box").fadeToggle();
});
Practical Example:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fading Effects in jQuery</title>
<style>
#box {
width: 200px;
height: 200px;
background-color: lightcoral;
margin: 20px auto;
display: none; /* Initially hidden */
text-align: center;
line-height: 200px;
border: 2px solid darkred;
}
</style>
</head>
<body>
<button id="fade-in">Fade In</button>
<button id="fade-out">Fade Out</button>
<button id="fade-toggle">Fade Toggle</button>
<div id="box">Fade Effect Box</div>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function () {
// Fade in
$("#fade-in").click(function () {
$("#box").fadeIn();
});
// Fade out
$("#fade-out").click(function () {
$("#box").fadeOut();
});
// Toggle fade effect
$("#fade-toggle").click(function () {
$("#box").fadeToggle();
});
});
</script>
</body>
</html>
Summary
- .fadeIn(): Gradually makes an element visible.
- .fadeOut(): Gradually hides an element.
- .fadeToggle(): Toggles the fade effect between showing and hiding.