Home > JQuery, Solutions Log > Adding JQuery Slider Part II

Adding JQuery Slider Part II

In my last post I showed how to easily add slider functionality using JQuery. In this post I will showcase some of the options that slider provides with a Temperature Converter. This is how it will work: the slider represents temperature measured in Celsius units and ranges between 0 and 100. As the user drags the slider, we will display the temperature equivalent in Fahrenheit.

Lets start by registering a basic slider:

   <script type="text/javascript">
	$(function()
	{
		$("#slider").slider();
	});
   </script>

Since the slider converts temperatures in the range 0 celsius and 100 celsius, modify the slider definition to include the range:

	$("#slider").slider({
		min: 0,
		max: 100,
		step: 1
		
	});

The next step is to add two span tags to display the chosen temperature and the temperature in Fahrenheit:

	Temperature in Celsius: <span id="celsius">0</span>
	
Temperature in Fahrenheit: <span id="fahrenheit"></span>

Finally all we need to do would be to captrue the slide event so that we can update the span tags:

	$("#slider").slider({
		min: 0,
		max: 100,
		step: 1,
		slide: handleSlide
	});

The handleSlide is a javascript function that looks like this:

	function handleSlide(event, ui)
	{
		// Update the celsius span
		$("#celsius").html(ui.value);

		// Compute the fahrenheit equivalent
		var fTemp = (1.8 * ui.value) + 32;

		// Just display the last two digits of the temp
		$("#fahrenheit").html(fTemp.toFixed(2));
	}	

Here is a working demo

Categories: JQuery, Solutions Log Tags:
  1. No comments yet.
  1. July 18th, 2012 at 04:41 | #1