Slowly moving the image

I have a balloon image. I need it to randomly fly around my page (this is a bit smaller). I only need this to fly to the top half of my page. I found the following code:

$("#Friends").animate({ top: "-=30px", }, duration ); 

But I'm not sure how I could loop it and make it go both along the x axis and along the y axis. Thanks if you can! I have jQuery enabled :)

+1
source share
4 answers

CSS

 #friends { position: absolute; } 

Markup

 <img src="http://jsfiddle.net/img/logo.png" id="friends"/> 

Js

 function moveit() { var newTop = Math.floor(Math.random()*350); var newLeft = Math.floor(Math.random()*1024); var newDuration = Math.floor(Math.random()*5000); $('#friends').animate({ top: newTop, left: newLeft, }, newDuration, function() { moveit(); }); } $(document).ready(function() { moveit(); }); 

Demo version: http://jsfiddle.net/W69s6/embedded/result/

More Live Demo: http://jsfiddle.net/9cN4C/

(the old demo is outdated and has a broken link, however, the code is still right, so it is left for reference and not for demonstration)

+3
source

How about something like that .... LIVE FIDDLE

HTML

 <img src="http://www.birdsnways.com/imgs/blbd48rt.gif" id="picture" /> 

CSS

 #picture{ position:absolute; } 

Js

 doNextPoint(); function doNextPoint(){ var maxX = $(window).width() - $('#picture').width(); var newX = rand(0, maxX); var maxY = ($(window).height()/2) - $('#picture').height(); var newY = rand(0, maxY); var speed = rand (1000, 3000); $('#picture').animate({ 'top': newY + 'px', 'left': newX + 'px' }, speed, function(){ doNextPoint(); }); } function rand (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } 
+5
source

You can paste this code into a named function and then add this function as a callback parameter for the animation, so it calls itself again after completion.

 var flying; flying = function() { $("#Friends").animate({ top: "-=30px", // you'll need to change this }, duration, flying ); } flying(); 

As it is, it will just keep flying up, because the animation should always go up 30 pixels. You will have to change the flight function to slightly randomize the movements. For more realism, keep the previous movement and just change it a bit (slight acceleration) so that it does not have very jerks.

+1
source

To encode it: use SetTimeout: https://developer.mozilla.org/en/window.setTimeout

For the x axis, use the CSS property left: (top: get the y axis)

0
source

All Articles