In this post we’re going to use jQuery UI to create a slider which will update a value in a text box. You may have already seen this concept in action on websites like confused.com
In a previous post we have discussed the benefits of using a hosted version of jQuery, in this example we will use the Google hosted version of jQuery and jQuery UI.
To begin, create a new html document using your favourite HTML editor like Dreamweaver.
Link to the hosted UI style sheet, this is required in the head section of you code:
To improve page load performance the JavaScript can be placed just before the body tag in your html:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
Next create a .js file which will contain the JavaScript to run once the webpage has loaded. The code below outlines two examples of sliders. A “slide” event is used to update the ID of a text input on form.
The second example illustrates some of the options available to sliders. Further details of option and events can be found on http://jqueryui.com/demos/slider/.
$(document).ready(function() { //slider example 1: a default slider $("#slider1").slider({ slide: function(event, ui) { $("#value1").val(ui.value); } }); $("#value1").val($("#slider1").slider("value")); //slider example 2 $("#slider2").slider({ min: 1, //minimum value max: 10, //maximum value value: 2, //default value slide: function(event, ui) { $("#value2").val(ui.value); } }); $("#value2").val($("#slider2").slider("value")); });
Don’t forget to include your .js file before the in your html.
Back to the html, as explained above our JavaScript updates a Text field on form. Below is the required html:
</pre> <form action="" method="get"><input id="value1" type="text" /> <div id="slider1"></div> <input id="value2" type="text" /> <div id="slider2"></div> </form> <pre>
Styling considerations: You want to hide the textboxes to visitors using JavaScript or this can be achieved using CSS.
One Comment
If you don’t want to use Jquery UI, you can use our very simple slider. Its only like 20 lines of code. http://codepsd.com/slider