Line25

Style Your Site According to the Weather with jQuery

Read the full post

By pulling in feed from the Yahoo API with jQuery, you can style your website according to the Weather! Find out how by following this step by step guide. We’ll start by creating four backgrounds for sun, rain, snow and cloudy, then use a clever jQuery script to pull in the forecast. To finish things off, we’ll even create a cool manual override, allowing users to switch through the various themes themselves.

See the weather switcher in action on Jakethelab.com

I recently put this idea into practice on a site I hashed together for my dog Jake. Jakethelab.com is a Tumblr blog where I post random photos and videos from my iPhone. The theme of the site changes depending on the weather, with Jake being the happiest when it’s sunny and cloudy, and not so much when it’s rainy or snowy. I wasn’t brainy enough to code all the Javascript myself, so some scripts from other talented developers were used alongside a few lines of my own basic jQuery. A few people has asked how it was all done, so here’s a brief overview.

Create the themes

Four backgrounds for each weather condition

The four themes of the site were put together as large background images. The same layout is used for each, but the overall theme changes to show the four weather conditions of sunny, rainy, snowy and cloudy.

Fetch the weather feed

$(document).ready(function() {	

$.YQL = function(query, callback) {
    var encodedQuery = encodeURIComponent(query.toLowerCase()),
        url = 'http://query.yahooapis.com/v1/public/yql?q='
            + encodedQuery + '&format=json&callback=?';
    $.getJSON(url, callback);
};
$.YQL("select * from rss where url='http://weather.yahooapis.com/forecastrss?p=UKXX0133'",function(data){
            var w=data.query.results.item;
          	var class=w.condition.text;
          	var encodedclass = class.replace(/\s+/g, '-').toLowerCase();
          	
          	$('body').addClass(encodedclass);
          	
       });    
});

The script that does all the work by fetching the feed from Yahoo is courtesy of Justin Shearer from Graphically Herding the Masses. Justin’s post takes the API to a more advanced level and creates a complete weather widget. For our site we only need part of the code, and the rest is modified to suit.

With our weather being used as a class on the page body, the condition needed encoding to lower case and the spaces removed. This changed the text from this: Partly Cloudy to this: partly-cloudy. Next, the encodedclass variable was then added as a class to the page body, so the HTML would read <body class="partly-cloudy">, which could then be styled up with CSS.

http://weather.yahooapis.com/forecastrss?p=USNY0996

If you’re using this code on your own site, you’ll want to change the location of the weather feed. The easiest way to find your location code is to head over to Yahoo weather and check the URL of the RSS feed for your particular location.

Write the CSS styles

body.cloudy, body.partly-cloudy, body.mostly-cloudy {
	background: #b3c6e4 url(Cloudy.jpg) fixed center bottom no-repeat;
}
body.rain, body.thunderstorms, body.drizzle, body.showers, body.thundershowers, body.scattered-showers, body.scattered-thunderstorms, body.isolated-thunderstorms {
	background: #9eacaf url(Rainy.jpg) fixed center bottom no-repeat;
}
body.sunny, body.fair, body.hot {
	background: #8cdafe url(Sunny.jpg) fixed center bottom no-repeat;
}
body.snow, body.mixed-rain-and-snow, body.mixed-rain-and-sleet, body.snow-flurries, body.light-snow-showers, body.blowing-snow, body.hail, body.sleet, body.snow-showers, body.heavy-snow {
	background: #889986 url(Snowy.jpg) fixed center bottom no-repeat;
}

With the current weather being injected right into our HTML, we can now write some CSS to make the appropriate changes to the website. Here’s where the list of Condition Codes from Yahoo Weather comes in handy because a bunch of classes are used to render each of the four backgrounds. For instance, a class of sunny, fair or hot will show the sunny background image. We don’t tend to get very many tropical storms in the UK, so just the most common conditions are picked out.

Add a manual override

Four buttons for changing the weather condition

Unless a user comes back to your website during every weather condition, they may never see your other themes so I figured it would be cool to add a manual override to allow users to toggle through the weather themselves.

<ul id="weather">
 	<li class="cloudy"><a href="#">Cloudy</a></li>
 	<li class="sunny"><a href="#">Sunny</a></li>
 	<li class="rainy"><a href="#">Rainy</a></li>
 	<li class="snowy"><a href="#">Snowy</a></li>
 </ul>

A simple list is laid out in HTML. Each list item contains an anchor which we’ll style up into button style graphics.

ul#weather {
		position: absolute; top: 40px; left: 40px;
		list-style: none; display: none;
	}
		ul#weather li {
			margin: 0 0 12px 0;
		}
			ul#weather li a {
				display: block; width: 60px;
				background: url(weather-icons.png) no-repeat; text-indent: -9999px;
			}
				ul#weather li.cloudy a {
					height: 32px; background-position: 0 0;
				}
				ul#weather li.sunny a {
					height: 63px; background-position: 0 -43px;
				}
				ul#weather li.rainy a {
					height: 50px; background-position: 0 -115px;
				}
				ul#weather li.snowy a {
					height: 48px; background-position: 0 -177px;
				}

The buttons are firstly moved into place using absolute positioning. This places them in a fixed position at the top left of the screen. Each anchor is then transformed into a button using CSS image replacement, with each button displaying a simple weather condition icon. Because this feature will only work if the user has Javascript enabled display:none; is used, the buttons will be made visible again by jQuery for those users with JS enabled.

	$('ul#weather').show();
	
	$('li.cloudy').click(function() {
		$('body').removeClass();
		$('body').addClass('cloudy');
		return false;	
	});
	$('li.sunny').click(function() {
		$('body').removeClass();
		$('body').addClass('sunny');
		return false;	
	});
	$('li.rainy').click(function() {
		$('body').removeClass();
		$('body').addClass('rain');	
		return false;
	});
	$('li.snowy').click(function() {
		$('body').removeClass();
		$('body').addClass('snow');	
		return false;
	});

A simple jQuery function is then written for each of the four buttons. When the button is clicked, the current class is removed from the page body and replaced according to whichever button was clicked. return false; disables the default action of the anchor to prevent the page from jumping back to the top.

var name = "#weather";  
    var menuYloc = null;  
   	menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px")))  
   		
   		$(window).scroll(function () {  
   			var offset = menuYloc+$(document).scrollTop()+"px";  
   			$(name).animate({top:offset},{duration:500,queue:false});  
		});  

To finish off the buttons, a nifty piece of code from Nettuts is used to transform the buttons into a floating menu, which slides up and down the page when the user scrolls.

See the weather switcher in action on Jakethelab.com

See it in action on jakethelab.com

Free web shadows pack for every subscriber

Join the mailing list to have new content delivered straight to your email inbox. Every subscriber gets a free pack of realistic web shadows.

Written by Chris Spooner

Chris Spooner is a designer who loves experimenting with new web design techniques collating creative website designs. Check out Chris' design tutorials and articles at Blog.SpoonGraphics or follow his daily findings on Twitter.

  • http://dougneiner.com Doug Neiner

    Hey Chris, great post as usual! I really enjoy your site and the amazing content!

    I noticed one problem with this code. It breaks in Safari because you use the reserved word "class" as a variable. Changing it to anything else will fix the problem.

    I actually put together a refactoring of your code here, and you are welcome to use as little or as much of it as you want: https://gist.github.com/98b9624d8596662e7ece

    You will need to up your jQuery version on JakeTheLab.com from 1.4.1 to 1.4.2 if you want to use the refactor since I use 'delegate'.

    Again, awesome concept… its the details like this that can take a good site and really add a personality to it.

    • http://twitter.com/chrisspooner Chris Spooner

      Thanks Doug! Your jQuery knowledge is definitely far more superior to mine. You seem to actually know what you're doing haha :-)
      I never knew about the issue with 'class', but I'll keep that in mind for any future jQuery hashing I do.

  • http://www.dynamicwp.net Eko Setiawan

    Thanks Chris, really like this concept…very creative

  • http://www.tropicaweb.co.uk Paul Maloney

    Cheers Chris, I usually do my switching with PHP, this offers a nice flexible alternative!

    @doug nice fix mate, much appreciated :)

  • http://www.emmi-nail.bg ноктопластика

    Heheh that's funny. I'll try it :) Thanks for sharin' man

  • http://www.antoineguedes.com Antoine Guédès

    This tutorial post is really original and funny Chris!
    It's nice to see some fresh things like this.

  • http://www.smashingshare.com Waheed Akhtar

    Thanks Chris for this beautiful and creative post!

  • http://www.alan-horne.com/blog Alan

    Amazing post Chris, the inovation in this is fantastic.

  • Abhishek parikh

    Thanks Chris for this beautiful and creative post!

    Amazing post Chris, the innovation in this is fantastic.

  • http://iainspad.com iainspad

    Nice one Chris! I've been wondering about this for a while, since I notice multiple backgrounds and mabual overrides for them are a big trend right now :D

  • http://www.rochelledancel.com Rochelle Dancel

    As usual, a great creative real-world mash-up. Thanks!

  • Adam

    Is there a way to take this a step further and call up the local weather for the user viewing the page?

    Perhaps an IP lookup to find the users region?

    It would make the experience much more personal; the weather in the region the website is hosted in is pretty meaningless to the user if they aren't also in the same region.

    • Laz

      I second this! Couldn't it be possible, maybe, to use html5 geolocation? (Well, it's not *strictly* HTML5, buy everybody calls it like that.)

    • http://www.spafu.nl Arash

      I was thinking the same thing. Get weather based on user location.

  • http://dtsn.co.uk Daniel

    Here's a post on the Yahoo Developer Network blog about getting the weather through YQL (in a lot more detail) http://developer.yahoo.net/blog/archives/2009/12/extending_the_weather_api_with_yql.html

  • http://www.loudamedia.com James Scott

    Haha this is so cool. I need to find a client that this would work for!

  • http://www.kensfi.com Ken the Tech

    Hey Chris but this is a fantastic idea! I have been seen websites changing the colors based of the day/night but I never heard about changing based on weather.

    It can slow down a bit the website but for sure is a nice idea.

    thx :)

  • http://loganlape.com Logan Lape

    Way to go Chris! I'm working on a busy site redesign now and just last week was joking with a co-worker about putting off important coding to have our site react to weather. Ironic to see if pop up now.

    The Nevada Museum of Art redesigned this year and use the local temperature to determine the color of their layout: http://www.nevadaart.org/

    Super subtle use of this concept but I enjoy it.

  • http://knowledgecity.com Jae Xavier

    I'd imagine this can be adapted to time of day, season, and stock market prices (lol!).

    I'm bookmarking this :)

  • http://lord-dhu.blogspot.com Bali (@ Indonesia)

    I Love This Site.. Thank's very much..

  • Niklas

    Truly awesome concept! Love it! You rock!

  • http://www.searchoptimist.co.uk Chris Malchenko

    Wow, this is a really great tutorial mate!

    It's especially cool to use it for a site with mostly local audience I guess as in the UK, where I live, the weather within 40 mile radius can differ quite a lot.

  • http://wpevolved.com Dan

    This is a really neat effect. I checked out the live effect on Jake's site and I must admit, I got deeply pulled into it. Who knew the life of a black lab could be so entertaining lol.

    Nice tut.

  • http://www.webdesignkc.co.uk/ Rory

    Nice bit of Jquery, your a diamond Chris much appreciated

  • http://singlecelldesign.com Karl

    Thanks Chris,

    This is really neat – I was looking at incorporating this into an upcoming holiday blog of mine so great timing! It worked great yesterday using the default coding but today the weather class is "partly-cloudy/windy" which clearly won't work. Does anyone have a crafty Friday fix that extends the example to ensure no forward slashes creep in?

  • http://www.checker24.info checker24

    great idea in connection with jQuery is a beautiful effekt.thanks

  • http://www.topstyle.com.br/ Web Design Curitiba

    Creative! Thx for posting, nice blog, bookmarked.

  • http://matthewleak.co.uk Matthew Leak

    I guess you're going to be needing the rainy/cloudy one a lot for here in the UK.

    Awesome tutorial too, as always..

  • http://www.pixelfish.co.uk/ Joe

    Interesting to say the least. I might have to recommend it to my web design friends in Bournemouth: http://www.pixelfish.co.uk/.

  • http://www.espreson.com Espreson

    such an awesome tutorial..

  • http://www.thedevelopertuts.com Bratu Sebastian

    Not that's a really cool idea for a website.

    Now you could make it rain with flash :)

  • http://www.designbysoap.co.uk Designbysoap

    haha, this is an amazing idea, i wonder what else you could link it to? perhaps a news feed, it could pick out words and decide whether it was a 'good' or 'bad' day, then colour the site accordingly. Couldn't you also use it for changing other elements, text for example?

  • http://www.madomat.com Madomat

    Hi Chris,
    Check out the use of time & weather backgrounds here: http://www.informationdesignassociation.org

    Simple but powerful!