I have an image inside of a div
. I would like to use some kind of timer to move the image to various positions inside of the div
.
Example html:
<div id="Container" width="200" height="100"><img src="..."></div>
I whipped something up with jQuery. What's interesting is that I started by animating top
and left
simultaneously, and after some effort and trigonometry, I realized that if you separate the x and y components, the animation of bouncing around in a div becomes a lot easier.
Demo: http://jsfiddle.net/jtbowden/DcgwR/
Here is a version that can handle multiple elements:
Demo: http://jsfiddle.net/jtbowden/DcgwR/2/
The key piece of code is:
// Parameters
// img: jQuery element (not necessarily img)
// speed: in px/millisecond
// max: maximum distance to travel
// dir: 'left' or 'top'
function bounce(img, speed, max, dir) {
speed += ((Math.random() * varSpeed) - (varSpeed / 2));
speed = speed < minSpeed ? minSpeed : (speed > maxSpeed ? maxSpeed : speed)
var time = max / speed;
var position = img.position();
var target = (position[dir] < 2) ? max : 0;
var style = {
queue: false
};
style[dir] = target;
img.animate(style, {
duration: time,
queue: false,
easing: "linear",
complete: function() {
bounce(img, time, max, dir);
}
});
}
maxSpeed
, minSpeed
, varSpeed
are defined globally (in px/ms), with varSpeed
being how much the speed varies at each bounce. I have a separate function startBounce
which calls bounce
twice, once for left
and once for top
. Because the animations are not queued, they animate independently.