Skip to content

Instantly share code, notes, and snippets.

@deanh
Created October 1, 2011 21:35
Show Gist options
  • Save deanh/1256683 to your computer and use it in GitHub Desktop.
Save deanh/1256683 to your computer and use it in GitHub Desktop.
Animation example for Ryan
<!DOCTYPE html>
<html lang="en">
<head><title>JS DOM Animation Example</title></head>
<style>
body {
margin: 0;
padding: 0;
}
#bg-image {
position: absolute;
top: 0;
left: 0;
background-color: #333;
width: 800px;
height: 600px;
z-index: 0;
}
.box {
position:absolute;
width: 10px;
height: 10px;
top: 50px;
left: 50px;
background-color: #fdd;
z-index: 100;
}
</style>
<body>
<div id="container">
<div id="bg-image"></div>
</div>
<!-- //
// use google's jquery if you have internet access!
// https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js
//-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var Shape = function () {};
// a basic example of using jQuery to animate an element
// just using the module pattern to contain scope.
(function () {
var cnt = 0;
var anim_time = 1000;
var rand_int = function (max) {
return Math.floor(Math.random()*max);
};
// use this if you want to set random fills
var rand_fill = function () {
var fill = "rgba(" + rand_int(255) + ',' +
rand_int(255) + ',' +
rand_int(255) + ',1.0)';
return fill;
};
Shape.prototype = {
id: undefined,
add_to_dom: function () {
var id = "box-" + cnt;
var div = '<div class="box" id="' + id + '"></div>'
$('#container').append(div);
this.id = '#' + id;
cnt++;
},
move_to: function (x, y, callback) {
var el = $(this.id);
if (el === undefined)
return;
el.animate({
left: x,
top: y
}, anim_time, function () {
if (callback !== undefined)
callback(el);
})
},
move_to_rand: function () {
this.move_to(rand_int(800), rand_int(600));
}
}
})();
// code wrapped below is not executed until the DOM is ready
$(document).ready(function () {
var s1 = new Shape();
var s2 = new Shape();
s1.add_to_dom();
s2.add_to_dom();
setInterval(function () {
s1.move_to_rand(); s2.move_to_rand();
}, 1020)
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment