Flickr Falling Cupcakes Demo
16th February 2012 · Last updated: 9th May 2012
I was proud of my demo, but I needed to get permission from the good folks at Flickr before publishing it here, as it uses their cupcake image. Luckily they agreed. Before I explain how the demo works, please note:
The cupcake graphic used in the demo is Copyright © 2012 Yahoo!
If you make use of my demo, the code of which I provide freely, then please change the cupcake graphic to one of your own. Thank you!
How It Works
I've added comments in the code so you can see what does what. I'll explain it briefly now here.
Next the cakes are moved down by one pixel. I also add a wobble to the left or right of one pixel to give them a bit of life. To move them, I get the
style of each div via the DOM:
var y = document.getElementById('cake' + cakeId);
var where = y.getAttribute('style');
(cakeId is just the ID of the div in the HTML, from 1 to 10.)
This gives me the current position of the div as a string. I then split the string down to extract the top and left styles of the div. That's so I can increment the top position (so the div moves down) and reapply the style to the div, again via the DOM:
y.setAttribute('style','top:' + ytop2 + 'px; left:' + yleft2 + 'px;');
I also check if the div has gone too far down the screen. If it has, then I reposition it randomly out of sight at the top, just like at the start. I found this gives the effect of a continuous flow of cupcakes falling down the screen!
Lastly, I set an interval timer of 25 milliseconds in my script. This slows the demo down just enough to give a smooth animation.