1

I am trying to create an effect of bubbles slowly rising to the top of the screen, what I have at the moment is this,

http://jsfiddle.net/PMF7k/

(Not sure why it isn't working, but you get the jist of the way I am currently planning on tackling this.)

function bubbles() {
$(".bubble").animate({
    'background': "rgba(0,0,0,0.4)",
        'top': '-300px'
}, 200);
}

bubbles();
setInterval(function () {
bubbles();
}, 200);

My question is that is there an effective way of being able to reuse the elements that go off the screen? For example when bubble A isn't view-able by the browser window, it goes to the bottom and repeats its cycle again?

Also as a brief side question, is it best to animate it via jQuery, wrap it in a function and constantly call it using setInterval?

  • duplicate of [Can jquery animations be chained programmatically?](http://stackoverflow.com/questions/12436701/can-jquery-animations-be-chained-programmatically), [How do i run the .animate function in jQuery forever?](http://stackoverflow.com/q/1206308/1048572), or [How to make a jquery infinite animation?](http://stackoverflow.com/q/4713477/1048572) – Bergi Feb 24 '13 at 20:22
  • This doesn't seem to be about making "infinite" animations; it's about reusing the animated-off-the-screen elements, or moving them back down to the bottom. Voting to leave open. – cHao Feb 25 '13 at 19:38

1 Answers1

0

jquery's animate

http://api.jquery.com/animate/

lets you specify a callback function that will be invoked upon animation completion.

Setup a callback that resets the position of the bubble and specify that callback as the complete parameter of animate

You'll want also the callback to re-invoke animate to restart the animation (you don't need setInterval).

Optionally initial position (x and y), speed, color, etc.. may be changed randomly.

Add many bubbles as you like, call the animate jquery method for each one.

btw: the jsfiddle doesn't work because you didn't specify to load jquery

Paolo
  • 15,233
  • 27
  • 70
  • 91
  • Okay this sounds good, but what about multiple bubbles with different timings and speeds, should I make an animation and function loop for each? – user1666881 Feb 24 '13 at 20:10
  • Can you provide a jsfiddle? I don't really understand. Thank you for your answer. – user1666881 Feb 24 '13 at 20:43