jQuery fadeToggle() Effect

The jQuery fadeToggle() method effect toggles between the fadeIn() and fadeOut() methods of the selected element. If the elements are faded out, the fadeToggle() will fade them in and if the elements are faded in, the fadeToggle() will fade them out.



Syntax of fadeToggle() effect

$(selector).fadeToggle(speed, easing, callback)

The selector is the element on which fadeToggle effect occurs. The speed parameter specifies the duration of the effect either in milliseconds or a few predefined strings, slow and fast. The optional easing is used to specify the speed of element to different points of animation. The possible value of easing are "swing" and "linear". The default value is swing. The optional callback parameter is the name of a function to be executed after the fading completes.



Example of fadeToggle() Effect

In the following example, we have used a box to apply the fading effects. The effect takes place when the 'Start Fading' button is clicked because fadeToggle() method is called inside button click function. This button fades out the box and when clicked again, it fades in the box.

<style>
.demobox { 
width: 200px; 
height: 150px; 
background-color: #CCFFFF;
border: 4px solid black;
display: none;
padding: 20px;
}
</style>

<div id="demo" class="demobox"> Hello World!</div>
<button id="btn">Start Fading Toggle</button>

<script>
(function( $ ) {
$("button#btn").click(function() {
$("div#demo").fadeToggle();
});
})(jQuery);
</script>

Output of the above code

Hello World!


In the above example, when the user click on the 'Start Fading' button, the div box of 'demo' id first gets faded in and on second click it faded out and continuously on click it toggles between fadeIn and fadeOut.





Example of fadeToggle() with speed

Here, we have specified the speed parameter to control how long the fading animation will run. We can either use the predefined string "slow" or "fast" or in a number in milliseconds. We have also specified the easing value "linear".

<p id="para">Welcome to etutorialspoint!</p>
<button id="btn1">Fade Toggle</button>

<script>
(function( $ ) {
$("button#btn1").click(function() {
$("p#para").fadeToggle("slow", "linear");
});
})(jQuery);
</script>

Output of the above code -

Welcome to etutorialspoint!





Example jQuery fadeToggle() callback

Here, we have specified a function as a callback parameter to the fadeToggle() method, it shows an alert when the effect is complete.

<p id="para1">Welcome to etutorialspoint!</p>
<button id="btn2">Start Fading Toggle</button>

<script>
(function( $ ) {
$("button#btn2").click(function() {
$("p#para1").fadeToggle("slow",  function(){
      alert("FadeToggle effect finished.");
    });
});
})(jQuery);
</script>


Read more articles


General Knowledge



Learn Popular Language