<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Animating Element</title>
<script type="text/javascript">
function move() {
var elem = document.getElementById('example_block'),
left = 0,
forward = true,
fps_30 = 1000 / 30, // 30 fps
id, amountN,
// editable settings
max_left = 660, // the farthest in px it will move to the right
amount = 2; // the amount in px it will move each interval (currently 30 fps)
function animate() {
// add amount if forward is true.
// if not, subtract 1 by adding negative amount.
left += forward === true ? amount : amountN;
elem.style.left = left + 'px';
if (left >= max_left && forward === true) { // check finish condition
forward = false; // make it go in reverse
} else if (left <= 0 && forward === false) {
// comment out the line below if you want it to keep
// going back and forth
clearInterval(id);
forward = true;
}
}
// get a negative amount to subtract from left
// for moving the element in reverse
amountN = amount - amount - amount;
// move 2 pixels every 30th of a second (30 fps)
id = setInterval(function() {
// run our animate() function in a separate execution
// context to minimize delay and drift
setTimeout(animate, 0);
}, fps_30); // draw every 10ms
}
window.onload = move;
</script>
<style type="text/css">
body {
background-color: #EEEEEE;
margin: 0;
}
</style>
</head>
<body>
<div class="example_path">
<div id="example_block" style="position: absolute; top: 0; padding: 20px;">Hello</div>
</div>
</body>
</html>