Start and Stop an Animation in jQuery

Starting and Stopping a jQuery Animation is as simple as using the animate() and stop() functions, as shown in the example below:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Start and Stop an Animation using jQuery</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
   1:  
   2:     
</script>
   1:  
   2:     <style type="text/css">
   3:         div { 
   4:             background-color:#ffeecc; 
   5:             width:100px; 
   6:             height:100px;
   7:         }
   8:     </style>
   9:     <script type="text/javascript">
  10:         $(function () {
  11:             $('#btnStart').click(function () {
  12:                 $('#divOne').animate({
  13:                     width: "200px",
  14:                     height: "300px"
  15:                 }, 5000);
  16:             });
  17:  
  18:             $('#btnStop').click(function () {
  19:                 $('#divOne').stop();
  20:             });
  21:         });
  22:     
</script>
</head>
<body>
<input id="btnStart" type="button" value="Start" />
<input id="btnStop" type="button" value="Stop" />
<br /><br />
<div id="divOne" />

</body>
</html>


As you can see, when the user hits the Start Button, we first start animating the Height and Width of ‘divOne’, using the animate() function. On clicking the Stop button, we use the stop() function to stop the animation.

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: