How I Made the Cloud Thing

I’ve already been asked several times how I did the floating cloud bit in the header, so here it goes. Fair warning: if you were expecting some miraculous bit of coding here you’re going to be sorely disappointed.

First, I’m using jQuery for this, so stick a reference to the Google CDN in your head.

1
2
3
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">

</script>


Happy cloud is happy.

Next, you need an image to go blundering about on your web page. If you don’t want it to obscure the page underneath it, you’re going to have to do some creative transparency. Here I made a cloud with a radial shading so the edges are less transparent than the middle. But you could use or make anything you want here. I used and recommend Inkscape if you don’t have a favorite vector graphics editor yet.

We’re going to use the image as a background to a div, which you should stick in whatever container div you want the image to roam around in, probably at the bottom. I stuck it in a div creatively named “page-head”.

1
2

<div id="cloud"></div>

Now let’s style that div a bit.

1
2
3
4
5
6
7
8
9
10

/* moving image */
#cloud {
position: relative;
top: 10px;
left: 0;
width: 299px;
height: 173px;
background: transparent url(img/cloud.png) no-repeat scroll 0 0;
}

Nothing special here. Use the top property to move the image up or down to where you want it. Note I’m setting the left property even though I’m starting it the default (0). This is important as you’ll see in a minute.

Now on to the JavaScript.

1
2
3
4
5
6
7
8
9

$(document).ready(function() {
animateCloud();
});

function animateCloud() {
$("#cloud").animate({
'left':  $("#page-head").width() - $("#cloud").width() - parseInt($("#cloud").css("left")) }, 50000, 'linear', function() {            animateCloud();        });
}

When the page is ready, we call the animateCloud function. From there we’re running a jQuery animation where we change the left property of the could by the container width - the width of the cloud image - the current left property of the image. So when the image is at the starting position, we get the width of the container - the width of the cloud div, since the starting left property of the cloud is 0. This is why we had to specify the position even though it’s 0 - if you didn’t, jQuery would return a NaN for this value. So the image goes across the screen over the course of 50 seconds (50000ms), and when it gets to the end it calls itself again. This time we set the left to 0, since container width - cloud div width - cloud div left property will equal 0. Back it moves, calls itself, ad nauseam.

Told you you’d be disappointed.