Build Internet has a brand new theme, and that's only the beginning. Read the full story or hide this bar

Build a Thermometer Controlled Page with jQuery

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.

Wordpress.com stats not installed! Posted Thursday, October 15th, 2009 / Back to Top

I this post. Tweet
SPONSOR

25 Comments 6 Mentions

  1. Eric B. Author Editor

    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 =-.

    October 15, 2009 · Reply

  2. moabi Author Editor

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

    October 16, 2009 · Reply

  3. Art Armstrong Author Editor

    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 =-.

    October 16, 2009 · Reply

  4. Greg Author Editor

    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

    October 16, 2009 · Reply

  5. Miba Author Editor

    Awesome!!

    October 17, 2009 · Reply

  6. Tomas Author Editor

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

    October 17, 2009 · Reply

  7. George Author Editor

    Just a thought – Switch/case statements on this?

    October 18, 2009 · Reply

  8. Zach Dunn Author Editor

    @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.

    October 18, 2009 · Reply

  9. George Author Editor

    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;
    }

    October 18, 2009 · Reply

  10. Simon Wells Author Editor

    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 =-.

    October 22, 2009 · Reply

  11. Vunky Author Editor

    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 =-.

    October 28, 2009 · Reply

  12. unrealxlife Author Editor

    wuawww =) Very Nice Thanks

    October 29, 2009 · Reply

  13. Greg Author Editor

    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 =-.

    November 5, 2009 · Reply

  14. Omer Rosenbaum Author Editor

    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?

    December 15, 2009 · Reply

  15. Ruana Author Editor

    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.

    February 10, 2010 · Reply

  16. Bruno Author Editor

    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?

    March 25, 2010 · Reply

  17. Zach Dunn Author Editor

    @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!

    March 25, 2010 · Reply

  18. jerrytm Author Editor

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

    April 14, 2010 · Reply

  19. andy@jordan 1 shoes Author Editor

    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

    June 10, 2010 · Reply

  20. volkan Author Editor

    really good :)

    September 3, 2010 · Reply

  21. Neil Author Editor

    Hi Zach
    I’d love to see this working but there is no js in the download and no slider in the demo.
    thanks

    November 8, 2010 · Reply

    • Zach Dunn Author Editor

      Thanks for the heads up. I’ll try to get a working jQuery file into the demo since the externally hosted ones now seem to be broken.

      November 8, 2010 · Reply

      • Ashley Author Editor

        Would love to see the live demo…wasn’t sure if it might be up soon or not. :) -Ashley

        December 2, 2010 ·

  22. Genevive Staber Author Editor

    Thanks very a lot for this nice put up;this is the sort of factor that keeps me going by way of these day. I’ve been wanting round for this web site after being referred to them from a buddy and was pleased when I found it after searching for some time. Being a avid blogger, I’m pleased to see others taking initivative and contributing to the community. Simply wanted to remark to point out my appreciation on your article as it’s very appleaing, and many writers do not get authorization they deserve. I am positive I’ll drop by once more and will recommend to my friends.

    May 26, 2011 · Reply

  23. davetiye Author Editor

    Is it still working?

    April 13, 2013 · Reply

 

Join the Conversation

Back to Top / Comment RSS

2012 Build Internet. Created by One Mighty Roar. Icons by Komodo Media. Back to Top