jQuery and Javascript power!
Friday, June 12th, 2009This is just a quick blog today, but I have been messing around with jQuery/AJAX functionality and what not. This is not something that someone else couldn’t do with a couple of minutes of free time to read.
Here is a snippet of code, using jQuery/Javascript to make an image randomly move about in a container. I’m assuming that you have the plugin livequery added into your jQuery script as well.
HTML
#imgShow {
position: relative;
overflow: hidden;
width: 656px;
height: 255px;
}
#imgShow img {
position: absolute;
top: 0;
left: 0;
}
<div id="imgShow"><img src="/images/test.jpg" alt="" /></div>
Javascript:
function timedGallery() {
$("#imgShow img").livequery(function() {
var maxWidth = 656;
var maxHeight = $("#imgShow").height();
var imgHeight = $(this).height();
var imgWidth = $(this).width();
var maxLeft = maxWidth - imgWidth;
var maxTop = maxHeight - imgHeight;
$(this).animate({ left: Math.round(Math.random() * maxLeft), top: Math.round(Math.random() * maxTop) }, Math.round(Math.random() * 8000 + 3500), timedGallery);
});
}
The run down with the above math is actually pretty simple. Math.random() generates a random number between 0 and 1. Then you can multiply by a number to receive a minimum (0) and max (max[left/top]). Basically: Math.round(Math.random() * 8000 + 3500) means, pick a random number between 0 and 11500. In this case, 0 - 11.5 seconds.
That is all for now, hope all is well!
Side note: In the interest of learning, I created a pretty nifty interface for fun. I tested it on Internet Explorer and it fails horribly. But, if you have FireFox, feel free to check it out: http://www.vipersuite.com
