w3resource
jquery exercises

jQuery: Change the color of any div that is animated

jQuery Fundamental - I : Exercise-22

Using jQuery change the color of any div that is animated.

<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<button id="button1">Click to see the effect</button>   
</body>
div {
    background: #B0E0E6;
    border: 1px solid #e30ae8;
    width: 20px;
    height: 30px;
    margin: 0 5px;
    float: left;
  }
  div.colored {
    background: #000000;
  }

Sample solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Change the color of any div that is animated.</title>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<button id="button1">Click to see the effect</button>
</body>
</html>

CSS Code:

button {
    display: block;
    margin: 20px 0 0 0;
    }   

div {
    background: #B0E0E6;
    border: 1px solid #e30ae8;
    width: 20px;
    height: 30px;
    margin: 0 5px;
    float: left;
  }
  div.colored {
    background: #000000;
  }

JavaScript Code :

$( "#button1" ).click(function() {
  $( "div:animated" ).toggleClass( "colored" );
});
 
function animateIt() {
  $( "#div1,#div2" ).slideToggle( "slow", animateIt );
}
 
animateIt();

Used Methods :

  • .slideToggle() : Display or hide the matched elements with a sliding motion.
  • .toggleClass : Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.

See the Pen jquery-fundamental-exercise-22 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Using jQuery animates the first div's left property and synchronizes the remaining divs.
Next: Using jQuery appends some text to all paragraphs.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming