JavaScript: Simple Animation

Javascript, Programing Add comments

This explain how can do whe do with a simple animation in JavaScript without script.aculo.us, moo.fx etc. Thought I highly recommend both these libraries and I really like animations done through them and I myself use script.aculo.us! I thought that it would also be good to know how they do it.

So let us start. We a are first making a simple HTML page with an image and a link to shrink that image we are also including a simple CSS file, prototype so that our code can be shorter and logic.js.

HTML:
  1.     <link rel=”stylesheet” type=”text/css” href=”res/ui.css”/>
  2.     <script src=”res/prototype.js”></script>
  3.     <script src=”res/logic.js”></script>
  4.   </head>
  5.     <p>Here we will try to make this image shrink with the help of prototype. You just need to click on the following <a href=”javascript:;” id=”link>link</a>.</p>
  6.     <img src=”img/rails.png” alt=”Rails” id=”rails”/>
  7.   </body>
  8. </html>

Our CSS file just includes padding and margin declarations for the body. Our JS file looks something like this:

JAVASCRIPT:
  1. Event.observe( window, 'load', function(){
  2.   $(’link’).onclick = shrinkImage;
  3. });
  4. shrinkImage = function(){
  5.   domID = ‘rails’;
  6.   var dimensions = $(domID).getDimensions();
  7.   function shrink(){
  8.     if(dimensions.height<0 || dimensions.width<0){
  9.       $(domID).hide();
  10.       return;
  11.     }
  12.     $(domID).height = $(domID).height-5;
  13.     setTimeout(shrink, 50)
  14.   }
  15.   setTimeout(shrink, 50)
  16. }}

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in