w3resource

jQuery Effect: Animate an element, by changing its height and width

jQuery Effect : Exercise-1 with Solution

Animate an element, by changing its height and width.
Sample Data :

HTML code:

<body>
 <button id="btn1">Animate height & width</button>
 <button id="btn2">Reset</button>
 <div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;"></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>Animate an element, by changing its height and width</title>
</head>
<body>
<button id="btn1">Animate height & width</button>
<button id="btn2">Reset</button>
<div id="box" style="background:#B45F04;height:100px;width:100px;margin:6px;"></div>
</body>
</html>

JavaScript Code :

$( "#btn1" ).click(function() {
  $( "#box" ).animate({
   width: "300px",
   height: "300px", 
    }, 1500 );
});

$( "#btn2" ).click(function() {
  $( "#box" ).animate({
   width: "100px",
   height: "100px",    
    }, 1500 );
});

Note :
In jQuery animate( properties [, duration ] [, easing ] [, complete ] ) method is used to perform a custom animation of a set of CSS properties. It has the following parameters :

  • properties : An object of CSS properties and values that the animation will move toward. [Type- PlainObject]
  • 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()]

The only required parameter is a plain object of CSS properties.

Live Demo:

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


Contribute your code and comments through Disqus.

Previous: jQuery Effects Exercises
Next: Stop an Animation.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.