Create A MooTools Slider With Spanning Element

The MooTools slider is a good little application, and creates a reliable means of adding in a slider tool to a site. However, one thing that the MooTool slider is missing is a block that covers what is on the left hand side of the slider, before the handle.

Create a page with the following HTML.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="./script/mootools.js"></script>
<link href="./style/slider.css" rel="stylesheet" type="text/css" />
<div id="track1">
<span id="track1span"></span><div id="handle1"><img src="./style/slider/handle.png" id="handle1Image" alt="Drag Me" /></div>
<p id="test"></p>
<script type="text/javascript" src="./script/slider.js"></script>

The slider element has the following structure.

div <- container for the slider
---span <- the span element
---div <- handle
------img <- image to make the handle pretty

You will need to download the MooTools library to run this tool.

Create a style file (called slider.css in a directory called style) and add the following content.

 background-color: #09f;
 margin:-20px 0 0 0;
 background-color: #222;

Now for the important part of the script. Create a file called slider.js in the script directory and add the following code in. I have put lots of comments in here to make it clear what each line is doing.

// set up track array
var handleArr = new Object();
handleArr["track1"]=250; // set initial value
// set up effects for the slider
var track1Span = new Fx.Style($('track1span'),'width',{duration:0});
var slider1 = new Slider($('track1'),$('handle1'),{
 steps:500,  // there are 250 steps in the track
 offset:0, // offset of zero fits the handle into the track
 onChange: function(pos){
 handleArr['track1'] = parseInt(pos); // store position
 updateTestDiv(); // run function to do something
}).set(handleArr["track1"]); // set initial position
// function to update test tag with handle position
function updateTestDiv(pos){
 $('test').innerHTML = handleArr['track1'];

All that this slider does is update a p tag with the id of test with the current position of the slider handle.

The ideal thing about this script is that it is fairly easy to add more tracks into it, you just need to duplicate the code slightly to create variables for slider2 and so on.

Add new comment

The content of this field is kept private and will not be shown publicly.
1 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.