Flickr Falling Cupcakes Demo

16th February 2012 · Last updated: 5th October 2016

Flickr recently celebrated eight years online by adding a cupcake to their logo. I wanted to click on the cake and see dozens of cakes falling down the screen, just like I remember happening once with snowflakes at Christmas time. I couldn't resist seeing if I could animate the cupcakes myself using JavaScript. I did it!


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.

First off, there aren't an infinite number of cupcakes you see falling! It looks like there are, but what you see are actually just ten divs. Each one contains the cupcake image. At the start of the demo, I get the screen height and width in JavaScript, then place the divs offscreen at the top. That's so you don't see them all at once. I also position them randomly across the screen and upwards out of view.

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.