Build a Thermometer Controlled Page with jQuery

Hold on. Before anyone gets too excited, jQuery does not have the ability to actually monitor a room’s temperature.

The thermometer we are building is a vertical slider from the jQuery UI library. As the temperature is changed on the thermometer, the page design will update accordingly.

The choice to go green in today’s post wasn’t random. Actually, it’s the result of an annual one day movement in the blogosphere…

It’s Blog Action Day!

This year, Blog Action Day has a focus on climate change.

When you spend most of your time building digital real estate, it’s often hard to realize the implications that a website can have on the real world. But then again, this is the same world where changing the background of Google could save massive amounts of energy. With impact like that, there’s steps even a simple web designer can take to safeguard against damaging climate change.

A Climate Oriented Tutorial

Today we’re doing our part to build awareness via themed tutorial. Chances are that you’ve already seen talk of conserving trees on other participating blogs. To mix things up, we’re going to celebrate nature by building our own miniature bio-dome.

The Goal

By the end of this tutorial, we’ll have a fully functioning temperature sensitive “Eco-Dome” built with the power of jQuery.

Eco Dome Demonstration

Quick disclaimer: I am not a climatologist. The temperatures used in the end product were not chosen scientifically. They are a rough guess at typical climate ranges. Build Internet is not the type of place you should studying for a science test.

In the interest of keeping this post at a reasonable length, I’ll only be explaining the elements of code that are directly relevant to this tutorial. If you get caught up in anything not explained here, please feel free to leave a comment.

The HTML

New File: Create “jquery-environment.html in the root directory

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

	<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>

	<!-- jQuery UI Libraries for Slider -->
	<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
  	<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script>

	<script type="text/javascript" src="jquery-environment.js"></script>

	<title>jQuery Environment</title>

	<link type="text/css" href="http://jqueryui.com/latest/themes/blitzer/ui.all.css" rel="stylesheet" />

	<link rel="stylesheet" href="jquery-environment.css" type="text/css" />

</head>

<body>

	<div id="wrapper">
		<div class="big-padding">

			<h1>The jQuery Eco-Dome</h1>

			<p class="instructions">Drag slider along the thermometer to change temperature.</p>

			<div id="temp-controller"></div>

			<div id="eco-dome">

				<p class="summary"><span class="current-climate">Moderate</span> / <span class="current-temp">50</span> °F</p>
				<p class="fact">Eleven of the twelve hottest years since thermometer readings became available occurred between 1995 and 2006 <a href="http://environment.nationalgeographic.com/environment/global-warming/gw-overview.html">Source</a></p>

			</div>

		</div>

	</div><!-- End of wrapper -->

	<!-- Hidden Content for Loading -->
	<ul id="climate-facts">
		<li id="rainforest-fact">One hectare (2.47 acres) may contain over 750 types of trees and 1500 species of higher plants <a href="http://www.rain-tree.com/facts.htm">Source</a></li>
		<li id="moderate-fact">Eleven of the twelve hottest years since thermometer readings became available occurred between 1995 and 2006 <a href="http://environment.nationalgeographic.com/environment/global-warming/gw-overview.html">Source</a></li>
		<li id="arctic-fact">Antarctica was imagined by the ancient Greeks, but not even seen until 1820 <a href="http://www.coolantarctica.com/Antarctica%20fact%20file/antarctica%20fact%20file%20index.htm">Source</a></li>
	</ul>

	<div id="image-bank">

		<img id="rainforest-image" src="images/rainforest-banner.jpg"/>
		<img id="moderate-image" src="images/moderate-banner.jpg"/>
		<img id="arctic-image" src="images/arctic-banner.jpg"/>

	</div>

	<!-- End of hidden content -->

</body>
</html>

Setup for this page’s structure is fairly straightforward. We’re putting in a series of spans, paragraphs, and images for the jQuery to put content in later. Each is identified by an ID to make targeting simple. I’ve put in the contents of “Moderate Climate” as a default value.

In order to reduce load times, all of the banner images (available in the source file) are loaded into a div tag which we will hide using CSS. Since the images are being loaded on pageview as opposed to the first jQuery call, loading should be much smoother.

The only other hidden section will be a list containing all of the “Fun Facts” to be displayed on top of the climate images. Just like the images, they will be pulled using jQuery.

The CSS

New File: Create “jquery-environment.css in the root directory

Nothing special in the CSS department. The only customization outside of fonts and alignment is with the slider class. The default slider is a little too thin for this project, so we’ve widened the entire element.

/* Styles for jQuery Eco-Dome Tutorial */
/* Zach Dunn (www.buildinternet.com) */

*{margin:0; padding:0;}

body{background:#5D7E2F url("images/moderate-bg.jpg") no-repeat top left;}

#wrapper{width:960px; margin:20px auto; background:#FFF; border:1px solid #DDD; overflow:hidden;}
	.big-padding{padding:30px;}

h1{font-family:Helvetica, arial, sans-serif; color:#191919;}

p{font-family: "Lucida Grande", arial, sans-serif; font-size:13px; color:#333;}
	p a{color:#A90000; text-decoration:none;}
		p a:hover{text-decoration: underline;}

/* Eco Dome Pieces */

	#eco-dome{width:750px; height:200px; background:#f7f7f7 url("images/moderate-banner.jpg") no-repeat top left; float:left; overflow:hidden;}
		#eco-dome p{color:#FFF; text-align: center; background:#000;}
			p.summary{font-size:21px; display:inline; margin-top:10px; float:left; padding:10px;}
			p.fact{display:inline; float:right; font-size:14px; padding:10px 0px; width:500px; clear:both; margin-top:60px;}
				p.fact a{font-style:italic; font-size:11px;}

	#temp-controller{float:left; margin:0px 30px;}

/* Navigation Pieces */

	.ui-slider-vertical{height:200px; width:80px; border:1px solid #DFDFDF;}
	.ui-slider .ui-slider-handle{width:90px; height:10px; border:1px solid #DFDFDF;}

/* Hidden Elements */

	#climate-facts, #image-bank{display:none;}

What’s this jQuery UI Business?

Some of you may be wondering what the difference is between jQuery and the UI. They are not the same thing, nor are they packaged together by default. jQuery UI is a separate library dedicated to user interface elements (e.g. Tabs, progress bars). In this tutorial we’re only using the slider element.

Each of these elements have themes that can be loaded in by default. As you can see in the html code above, we are using the “Blitzer” theme. It is loaded in from an external CSS file hosted on the UI server.

The jQuery

New File: Create “jquery-environment.js in the root directory

/* jQuery Eco-Dome Tutorial */
/* Zach Dunn (www.buildinternet.com) */

var climate;
var climate_fact;
var climate_banner;

function analyze_temperature(current_temp){

	//Determine current temperature range
	if (current_temp >= 0 && current_temp <= 32){

		//Arctic climate
		climate = "Arctic";

		//Get current banner
		climate_banner = $("#arctic-image").attr("src");

		$("#eco-dome").css({
			'background' : '#000 url("' + climate_banner + '") no-repeat top left'
		});

		$("body").css({
			'background' : '#285988 url("images/arctic-bg.jpg") no-repeat top left'
		});

		//Update displayed fact
		climate_fact = $("#arctic-fact").html();
		$(".fact").html(climate_fact);

	}else if (current_temp > 32 && current_temp < 75){

		//Moderate climate
		climate = "Moderate";

		//Get current banner
		climate_banner = $("#moderate-image").attr("src");

		$("#eco-dome").css({
			'background' : '#000 url("' + climate_banner + '") no-repeat top left'
		});

		$("body").css({
			'background' : '#5D7E2F url("images/moderate-bg.jpg") no-repeat top left'
		});

		//Update displayed fact
		climate_fact = $("#moderate-fact").html();
		$(".fact").html(climate_fact);

	}else{

		//Tropical climate
		climate = "Rainforest";

		//Get current banner
		climate_banner = $("#rainforest-image").attr("src");

		$("#eco-dome").css({
			'background' : '#000 url("' + climate_banner + '") no-repeat top left'
		});

		$("body").css({
			'background' : '#11170d url("images/rainforest-bg.jpg") no-repeat top left'
		});

		//Update displayed fact
		climate_fact = $("#rainforest-fact").html();
		$(".fact").html(climate_fact);

	}

}

function changeTemperature() {

	var current_temp = $("#temp-controller").slider("value");
	$(".current-temp").html(current_temp);

	//Determine climate from temperature
	analyze_temperature(current_temp);

	//Display climate title
	$(".current-climate").html(climate);

}

$(document).ready(function(){

	$("#temp-controller").slider({
		orientation: "vertical",
		range: "min",
		max: 100,
		min: 0,
		value: 50,
		slide: changeTemperature,
		change: changeTemperature
	});

});

Now that we’ve got all of the style and structure in place, it’s time to put an engine behind the visuals. The jQuery used below may look a little long, but it’s not terribly complex. I’ve broken down the flow below in sections to help you figure things out:

$(document).ready

  1. The div of #temp-controller is converted into a vertical slider. Whenever this slider is used (via slide and change parameters), it will trigger the changeTemperature function

changeTemperature Function

  1. The changeTemperature function assigns the current value of the slider to a variable called current_temp
  2. The current_temp variable is displayed into the “.current-temp” span tag
  3. The analyze_temperature function is called using the current temperature as an argument
  4. The climate name returned from analyze_temperature is displayed within the .current-climate span

analyze_temperature Function

  1. The current temperature (stored in current_temp) is filtered by current range
  2. Based on the temperature, a different style and climate name is assigned
  3. Style changes are done through the css jQuery method
  4. Images are pulled using src attributes of preloaded images in the hidden “image-bank” div

Environmentally Friendly Code

With some added ingenuity, you can adapt the concepts used in this tutorial to build your own slider-controlled content. Or digital terrarium. Whichever appeals to you more.

As of posting, I’ve only tested the result in Firefox in order to get a working version up. I’ll be revisiting it as needed to fix bugs in browsers from IE7 and up.

  • Stumble It!
  • Bookmark It!
  • Tweet it!

About Zach Dunn

Zach is a partner and interface designer at One Mighty Roar from Massachusetts, USA. Follow him on Twitter @zachdunn.

 

Discussion

  1. Eric B.

    October 15th, 2009 at 11:18 PM

    Looking pretty awesome! Though it would be cool to use jQuery to monitor the temperature in a room.

    Maybe we can find a way to make people cover up their webcams :P
    .-= Eric B.´s last blog ..Tips For Organizing Your CSS Files =-.

  2. moabi

    October 16th, 2009 at 8:19 AM

    wow,
    amazing…it gives plenty of ideas to use…

  3. Art Armstrong

    October 16th, 2009 at 12:32 PM

    Very cool idea. OCD thing I found was that when I tried to take it to 100 or 0 I had to go all the way to the top or bottom and then release to get it there although it would say its at 99 or 1. I could see this used in a lot of different ways though, including dates.
    .-= Art Armstrong´s last blog ..WordPress Custom Comment Display =-.

  4. Greg

    October 16th, 2009 at 2:38 PM

    What about making the transitions smoother with fading? Obviously the code would have to changed a bit since you couldn’t just change the background but it would look really good

  5. Miba

    October 17th, 2009 at 1:05 AM

    Awesome!!

  6. Tomas

    October 17th, 2009 at 9:47 AM

    Incredible! Thanks.
    .-= Tomas´s last blog ..26 jQuery Plugins for Superb Navigation =-.

  7. George

    October 18th, 2009 at 3:02 PM

    Just a thought – Switch/case statements on this?

  8. Zach Dunn

    October 18th, 2009 at 3:15 PM

    @George

    I had originally started with a switch statement, but cases cannot (to the best of my knowledge) contain multiple criteria. Since we’re sorting by temperature ranges, I opted for the if statement.

    If anyone has a suggestion for optimization, I’d be glad to hear it.

  9. George

    October 18th, 2009 at 10:41 PM

    Zach – you’re much more knowledgeable on this than I – but I ran across some suggestions that javascript switch cases might take ranges. Since I’ve got some need for this sort of code – your thoughts will be useful.

    maybe a modification of:
    http://www.irt.org/script/1618.htm

    (not fully fleshed out here.. but the idea might be)

    var current_temp

    switch (true) {

    case ((current_temp >= 0 && current_temp 32 && current_temp 75):
    alert(“hot”)
    //do something hot
    break;
    }

  10. Simon Wells

    October 22nd, 2009 at 5:45 AM

    This is awesome!!!.
    Could this be adapted for page layout changes?
    IE, when the slider moves to a marked scale positions the images show an example image of the expected page layout, then with a submit button it then reloads the page from a different css file that relate to that image?
    .-= Simon Wells´s last undefined ..If you register your site for free at =-.

  11. Vunky

    October 28th, 2009 at 9:46 AM

    You can do some funny stuff with that. I’m thinking of those coffee-cups which show a naked girl when they get hot ;)
    .-= Vunky´s last blog ..What I’ve been up to this summer =-.

  12. unrealxlife

    October 29th, 2009 at 4:47 AM

    wuawww =) Very Nice Thanks

  13. Greg

    November 5th, 2009 at 1:15 AM

    Granted I’m bone-tired and someone or the article itself may have mentioned this; however–

    A cool modification (not to the tutorial; the modification would ruin the intent of the tutorial!) would be to use one of the many available APIs out there to get the current temperature of your city, and modify elements based on that! Once winter hits here up in Ottawa, you’d have pretty much 5 months of the same background, but man… you could even make the various options rather granular if you had the ambition!
    .-= Greg´s last blog ..Coles First Halloween =-.

  14. Omer Rosenbaum

    December 15th, 2009 at 10:08 AM

    I am trying to add some sub degrees inside that range of temperatures.
    I added this one after the moderate:

    }else if (current_temp > 50 && current_temp < 65){

    //Dagbladet climate
    climate = "Dag";

    //Get current banner
    climate_banner = $("#dag-image").attr("src");

    $("#eco-dome").css({
    'background' : '#000 url("' + climate_banner + '") no-repeat top left'
    });

    $("body").css({
    'background' : '#000000 url("images/dag-bg.jpg") no-repeat top left'
    });

    //Update displayed fact
    climate_fact = $("#dag-fact").html();
    $(".fact").html(climate_fact);

    So now I have 4 levels, 0-32 (arctic), 32-50 (moderate), 50-65 ("dag" level) and then "else" which shows the rainforest.
    It works fine except when I put the handle on 50 and then shows the rainforest. On 51 it shows Dag until 65 degrees.
    Why is that and how can the 50 degrees can be part of the Dag level?

  15. Ruana

    February 10th, 2010 at 8:32 PM

    That’s pretty awesome. Unfortunately I would need a working version for IE too. Do you still have plans for revisiting it to fix bugs in IE? I get an error message when try to view the page in IE7 and although I’m a web designer I’m not good at coding in JQuery. I can’t figure it out myself.

  16. Bruno

    March 25th, 2010 at 9:52 AM

    Hi

    It’s not working for me… Tried under Chrome, Firefox and Opera… No slider or thermometer for me, under Ubuntu or Windows XP.

    Anyone?

  17. Zach Dunn

    March 25th, 2010 at 12:17 PM

    @Bruno

    You’re absolutely right. It would appear that something has caused the demo to break in the past couple months. I’ll check the jQuery and post a solution shortly!

  18. jerrytm

    April 14th, 2010 at 3:27 PM

    Bad link for Javascript in code. http://jqueryui.com/latest/ui/ui.slider.js and more doesn’t exist.

  19. andy@jordan 1 shoes

    June 10th, 2010 at 9:42 AM

    This would really be helpful on some code seekers they would surely love the post as it included some codes. This would be great Thanks

Join the Conversation!

Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.

CommentLuv is Enabled

 

Sponsors

Advertise on Build Internet!