jQuery is a JavaScript library that provides us with multiple features and tools to handle the HTML document. It is widely used as it is faster and more efficient in performing web development-related tasks, including object animations and event handling. To use jQuery, we must include its library in the HTML document. To include the library, write the following code:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
In this Answer, we will learn what is fadeToggle()
method in jQuery.
Note: To understand the concept better, you can first read the Answer on
fadeIn()
andfadeOut()
method.
fadeToggle()
methodWe use the fadeToggle()
method to toggle between fading in the element and fading it out.
The syntax of fadeToggle()
method is as follows:
$(selector).fadeToggle(fadeSpeed, fadeEasing, callbackFunction);
selector
: It is the element we want to apply the fadeToggle()
method on.
fadeSpeed
(optional): It is the speed of the toggle animation. We can set it to slow, fast, normal or give the milliseconds value.
fadeEasing
(optional): It is the speed at which our animation accelerates or decelerates. For example, we can set it to swing or linear.
callbackFunction
(optional): It is the function called after the animation has completed.
The following examples will help us better understand the fadeToggle()
method:
We use the fadeToggle()
method without parameters in the following code.
Let's understand what happens in the index.html
file:
Lines 3–5: We define the document's title
in the <head>
tag.
Line 7: We include the jQuery library.
Lines 8–14: We write the JavaScript code in the <script>
tag. The document.ready()
function executes after the DOM has loaded completely without making an explicit call. In this function, we call the fadeToggle()
method for the element with class name element
when the button with id toggleButton
is clicked.
Note: There are no parameters in the fadeToggle()
method so the default values for fadeSpeed
and FadeEasing
will be used which are 400
and swing
respectively.
Lines 16–23: We write all the styling code in the <style>
tag.
Lines 25–29: We create a <button>
and <div>
.
We use the fadeToggle()
method with parameters in the following code.
Let's understand what happens in the index.html
file:
Lines 8–16: We call the fadeToggle()
method for the element with class name element
when the button with id toggleButton
is clicked. The parameters in the fadeToggle()
method show that 5000
is the speed, swing
is the easing parameter, and function()
is the callback function that will be executed once the animation completes.
The fadeToggle()
function in jQuery provides a simple and convenient way to apply fade animation effects to elements in the HTML document. Using this function, we can easily toggle the visibility of elements with a smooth fade-in or fade-out transition.
Free Resources