w3resource

jQuery Effect: Toggle between fading in and fading out different boxes

jQuery Effect : Exercise-8 with Solution

Toggle between fading in and fading out different boxes

Sample Data :

HTML code:

<body>
<p>fadeToggle() with different speed parameters.</p>  
<button>Click to fade in/out boxes</button><br><br>
<div id="div1" style="width:100px;height:100px;background-color:#6D5050;"></div>
<br>
<div id="div2" style="width:100px;height:100px;background-color:#42D5A9;"></div>
<br>
<div id="div3" style="width:100px;height:100px;background-color:#8942D5;"></div>
</body>

Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Toggle between fading in and fading out different boxes</title>
</head>
<body>
<p>fadeToggle() with different speed parameters.</p>  
<button>Click to fade in/out boxes</button><br><br>
<div id="div1" style="width:100px;height:100px;background-color:#6D5050;"></div>
<br>
<div id="div2" style="width:100px;height:100px;background-color:#42D5A9;"></div>
<br>
<div id="div3" style="width:100px;height:100px;background-color:#8942D5;"></div>
</body>
</html>

JavaScript Code :


$("button").click(function(){
        $("#div1").fadeToggle();
        $("#div2").fadeToggle("slow");
        $("#div3").fadeToggle(4000);
    });

Note :
In jQuery fadeToggle( [duration ] [, easing ] [, complete ] ) method is used to display or hide the matched elements by animating their opacity. It has the following parameters :

  • duration : A string or number determining how long the animation will run. [Type- Number or String]
  • easing : A string indicating which easing function to use for the transition. [Type: String]
  • complete : A function to call once the animation is complete. [Type: Function()]

Live Demo:

See the Pen jquery-effect-exercise-8 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Write a jQuery Code to get a single element from a selection.
Next: Finish a currently running animation.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/jquery-exercises/jquery-effect-exercise-8.php