jQuery fadeToggle() method is used to toggle between fadeIn() and fadeOut() effects. If the selected elements are faded out, the fadeToggle will fade in them, if they are faded in, then it will make them fade out.
jQuery fadeToggle() Syntax
$(selector).fadeToggle(speed, callback_function);
$(selector): Selector which is used to select html elements on which this effect is being applied.
speed: Optional Parameter. Values can be in milliseconds or string values such as “slow” or “fast”.
callback_function: Optional parameter. This function executes when the toggle effect is complete.
jQuery fadeToggle() Example
In the following example, we have used paragraph selector to apply the effects on the paragraphs. The effect takes place when the button is clicked because fadeToggle() method is called inside button click function. Since fadeOut() method toggles between fadein and fadeout, the button fades out the paragraph and when clicked again, it fades in the same paragraph.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").fadeToggle(); }); }); </script> </head> <body> <h2>jQuery fadeToggle effect example</h2> <p>This tutorial is published on beginnersbook.com. This paragraph will fadeout when the FadeToggle button is clicked and it will fadein when the same button is clicked again.</p> <button>FadeToggle</button> </body> </html>
Output:
When the page is initially loaded:
After the FadeToggle button is clicked:
After the FadeToggle button is clicked again:
jQuery fadeToggle() Example with speed parameter
We can specify the speed of the effect in milliseconds or “slow” or “fast”. Here we have specified the speed as 3000 milliseconds.
$(document).ready(function(){ $("button").click(function(3000){ $("p").fadeToggle(); }); });
jQuery fadeToggle() method with speed and callback function parameters
Here we have specified a function as a callback parameter, it shows an alert when the effect is complete.
$(document).ready(function(){ $("button").click(function(){ $("p").fadeToggle("slow", function(){ alert("fadeToggle effect is complete"); }); }); });
Output:
Leave a Reply