JavaScript Weather

November 26, 2009

Here’s a crazy idea, what would you do if you wanted to change the background picture of your website so it matches the weather. Luckily Its really easy, and I figured out all the hard bits for you.

UPDATE - Chris Heilmann over at the Yahoo! Developer Network Blog has made this even simpler through the use of YQL.

The Data

First of all we need a data source which will provide the weather for a particular location, we can grab this from the Yahoo Weather API. Using the code UKXX0117 which is for Reading, UK I can create the an RSS feed which you can see here Great but how can we process this RSS feed? That’s where Yahoo Pipes comes in, we can take in the RSS feed extract the data we need (item.yweather.condition) and export it as JSON.

Now we can access the JSON data for the weather in Reading here.


The JavaScript cannot directly call the JSON script via AJAX due to cross site scripting limitations imposed by the browser. This is where JSONP comes in, JSONP is a way to retrieve data from external domains through wrapping the JSON in a function, you can read more on JSONP at from__future__import. Yahoo Pipes fully supports the JSONP format using the parameter callback, therefore in our webpage we load up the following.

<script type="text/javascript" src=""></script>

This will call the function weather passing through a weather status code as the parameter.

That is really it, you can do whatever you want with the data, here’s a quick example of how I would use it.

function weather(data) { 
        var code = data.value.items[0].content;
	switch(code) {
		case '32': $(document.body).addClassName('sunny');


comments powered by Disqus