What Does the jQuery fadeToggle() Method Do?
The jQuery fadeToggle() method toggles the visibility of
selected HTML elements by animating their opacity. If an element is
currently hidden, fadeToggle() gradually increases its
opacity to display it (similar to fadeIn()). If the element
is currently visible, it gradually decreases its opacity until the
element is hidden and set to display: none (similar to
fadeOut()). This article explains how the method works, its
syntax, available parameters, and how to implement it effectively.
How fadeToggle() Works
Under the hood, fadeToggle() checks the current display
state of the matched elements. It then performs the opposite action:
- Hidden elements transition smoothly from an opacity
of
0to1(or their original computed opacity), restoring their original CSS display property. - Visible elements transition from their current
opacity down to
0. Once the animation completes, the element's CSSdisplayproperty is set tonone, removing it from the document flow.
Syntax
The basic syntax for the fadeToggle() method is:
$(selector).fadeToggle(speed, easing, callback);Parameters
All parameters are optional:
speed: Determines the duration of the animation. It can be defined using strings like"slow"or"fast", or as an integer representing the time in milliseconds (e.g.,400,1000). The default duration is400milliseconds.easing: Specifies the speed pattern of the animation. The default values provided by jQuery are"swing"(slower at the beginning and end, faster in the middle) and"linear"(a constant speed throughout). Additional easing options can be added using external libraries such as jQuery UI.callback: A function that executes immediately after the fade animation finishes. It is called once per matched element.
Code Example
Here is a practical demonstration of using fadeToggle()
with a button click:
<button id="toggleBtn">Toggle Box</button>
<div id="box" style="width: 100px; height: 100px; background-color: blue;"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$("#toggleBtn").click(function() {
$("#box").fadeToggle("slow", function() {
console.log("Fade animation finished.");
});
});
</script>Key Considerations
- Layout Impact: Unlike CSS
visibility: hidden, which preserves the element's space on the page,fadeToggle()completely removes the element from the document flow usingdisplay: noneonce it has fully faded out. - Queue Handling: Multiple clicks in rapid succession
will queue animations. You can prevent animation build-up by chaining
the
.stop()method before toggling:$(selector).stop().fadeToggle().