Proper way to animate with JavaScript

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts:107

Proper way to animate with JavaScript

Hi there,
I would like a little advice for a proper way to animate with JavaScript, without using jQuery or other framework, just with pure JavaScript.
For example, i would like to do a basic horizontal moving on a Div. Let's say that the animation interval is 30ms. I would write it that way :

Code: Select all

var elm = document.getElementById('d1');
var x_pos = 0;
var x = 1;
setInterval(function() {
  if(x_pos < 0 || x_pos > 90) x = x * -1;
  x_pos += x;
  elm.style.left = x_pos +'%';
}, 30);
However, it seems to me that this method is not the best, because whenever you have complex animation, you'll have to chain setTimeout() inside setInterval() or inside other setTimeout().

Admin Posts:805
Hello,
The JavaScript has a function for animating objects, called requestAnimationFrame() that works in modern browsers (IE 10+).
requestAnimationFrame(function_name) only runs the given function once, you need to call it inside the function_name() if you want to make a UI change for the animation.
The function_name(time) can have a parameter, time, which is the timestmp in milliseconds.
Just do a search on google and there should be a ton of resources about requestAnimationFrame().

Here's an example with a bouncing element. Test it and check the comments in code to understand how the requestAnimationFrame works.

Code: Select all

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example requestAnimationFrame</title>
<style type="text/css">
#d1 {
 position: absolute;
 top: 100px;
 left: 1px;
 width: 70px;
 height: 70px;
 background: #33f;
 border-radius: 50%;
}
</style>
</head>
<body>

<div id="d1"></div>

<script>
var elm = document.getElementById('d1');
var x_pos = 0;
var y_pos = 2;
var x_speed = 1;  // higher value increase the speed
var y_speed = 1.4;  // higher value increase the speed

// bouncing elm for 4 seconds ( code from https://coursesweb.net/ )
function bounce(time){
  //calculate difference since last repaint (in milliseconds)
  var diff = time - start_time;

  // if less than 4 seconds
  if(diff < 4000) {
    // set values for x, y position
    if(x_pos < 0 || x_pos > 90) x_speed = x_speed * -1;
    if(y_pos < 0 || y_pos > 25) y_speed = y_speed * -1;
    x_pos += x_speed;
    y_pos += y_speed;

    // set left and top position
    elm.style.left = x_pos +'%';
    elm.style.top = y_pos +'%';

    requestAnimationFrame(bounce);  // call the next frame
  }
}

var start_time = window.performance.now();  // starting timestmp in milliseconds
requestAnimationFrame(bounce);  // call 1st frame
</script>

</body>
</html>

Similar Topics