jQuery - jQuery Fade Methods
jQuery provides fade effects to gradually change the opacity of elements, creating smooth fade-in and fade-out animations. These are more visually appealing than simply hiding or showing elements.
1. Basic jQuery Fade Methods
Method | Description |
---|---|
.fadeIn() |
Fades in hidden elements (from transparent to visible) |
.fadeOut() |
Fades out visible elements (from visible to transparent) |
.fadeToggle() |
Toggles between fadeIn and fadeOut |
.fadeTo() |
Fades to a specified opacity |
2. Basic Syntax
$(selector).fadeIn(speed, callback);
$(selector).fadeOut(speed, callback);
$(selector).fadeToggle(speed, callback);
$(selector).fadeTo(speed, opacity, callback);
-
selector
→ Target element(s) -
speed
→ Animation speed:"slow"
,"fast"
, or milliseconds (e.g., 1000) -
opacity
→ Value between0
(fully transparent) and1
(fully visible) -
callback
→ Optional function executed after the animation
3. Examples
A. .fadeIn()
Fades in a hidden element.
$("#fadeInBtn").click(function(){
$("#box").fadeIn("slow");
});
B. .fadeOut()
Fades out a visible element.
$("#fadeOutBtn").click(function(){
$("#box").fadeOut(1000); // 1 second
});
C. .fadeToggle()
Toggles fade in/out depending on current visibility.
$("#fadeToggleBtn").click(function(){
$("#box").fadeToggle("fast");
});
D. .fadeTo()
Fades to a specific opacity without changing display.
$("#fadeToBtn").click(function(){
$("#box").fadeTo(1000, 0.5); // Fade to 50% opacity
});
4. Using Callback Functions
Run a function after fade animation completes.
$("#fadeOutBtn").click(function(){
$("#box").fadeOut(1000, function(){
alert("Box is now hidden!");
});
});
5. Example: jQuery Fade Effects
<!DOCTYPE html>
<html>
<head>
<title>jQuery Fade Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
$("#fadeInBtn").click(function(){
$("#box").fadeIn("slow");
});
$("#fadeOutBtn").click(function(){
$("#box").fadeOut("slow");
});
$("#fadeToggleBtn").click(function(){
$("#box").fadeToggle(1000);
});
$("#fadeToBtn").click(function(){
$("#box").fadeTo(1000, 0.3);
});
});
</script>
</head>
<body>
<button id="fadeInBtn">Fade In</button>
<button id="fadeOutBtn">Fade Out</button>
<button id="fadeToggleBtn">Fade Toggle</button>
<button id="fadeToBtn">Fade To 30%</button>
<div id="box" style="width:200px; height:100px; background:skyblue; margin-top:10px; display:none;">
Hello jQuery Fade!
</div>
</body>
</html>
6. Summary of Fade Effects
-
.fadeIn()
→ Gradually shows hidden elements. -
.fadeOut()
→ Gradually hides visible elements. -
.fadeToggle()
→ Switches between fadeIn and fadeOut. -
.fadeTo()
→ Fades to a specific opacity. -
All methods can include speed and callback.