Scriptaculous slider trick

Last modified date

Comments: 15

Yesterday I was looking at the Scriptaculous library, in particular the slider bar. I had used it once before with some success, using a graphic for the track and gripper. But that’s was boring! What I wanted was to see the bar fill up with colour when it was slid. Something like this:

I hadn’t seen anything like this around (not saying it hasn’t been done, just that I hadn’t seen it!), so after a bit of playing I found out it was actually very easy to create. And this is how I did it…

All it really does is use a handy little trick with transparent PNG images and background-image positions. You can find details of what I mean in this handy article by Dave Stone, over at Bare Naked App.

So basically I have my slider gripper (or handle), which has a transparent background:

And the slider track, which has an opaque white background but is transparent where I want the colour to show through (thumbnail shown, but links through to full size image):

And then I have the background image, which is essentially double the size of the track and has one half in off-white and one in green (thumbnail shown, but links through to full size image):

The XHTML used for the slider looks like this:

[html]

[/html]

The CSS looks like this:

[css]#slider, #slider-bar, #slider-handle {
border: 0;
padding: 0;
margin: 0;
}
#slider {
width: 300px;
height:42px;
background: url(img/bg.gif) no-repeat -300px;
margin-left: 42px;
}
#slider-bar {
width:300px;
height:42px;
background: url(img/track.png) no-repeat;
}
#slider-handle {
width:42px;
height:42px;
cursor:move;
background: url(img/gripper.png) no-repeat;
}
#percent {
font-size: 75%;
font-family: arial;
font-weight: bold;
text-align: center;
padding-top: 1.1em;
}[/css]

And finally, the Javascript looks like this:

[javascript][/javascript]

You may notice the offset value, off. I’m using this because in my experiment the slider handle doesn’t fully cover the bar (nor did I want it to), so I cannot have the background image colour go fully across the track. I had to incrementally offset it depending on the position and size of the handle.

And that’s it! Pretty darned easy, but looks really neat. You can see it in action at http://dev.amnuts.com/slider/.

Share