July 19, 2007
ScrollSlider: Lightweight Slider Widget using Scrollbar
Posted by Kevinin under Extension, JavaScript, WidgetNo Comments
I’ve looked around the net for some JavaScript slider widgets, and I’ve noticed that many of them were part of a framework (YUI, script.aculo.us), not well written or not even free. So I’ve decided to write my own (not saying that using the sliders from a framework are evil, but including a whole framework just for one or two sliders isn’t that great). I finished a rather good one, but then I had an idea, which I spent quite some time on figuring out. I’ve ended up with a slider which actually (mis)uses a scrollbar. It’s a very lightweight widget, the compressed code is less than 1kb! Click on the picture to see some examples of it.
new ScrollSlider('id');
ScrollSlider works in all popular browsers
ScrollSlider only supports Integers, but it could be extended to use Floats or even using certain steps on the slider. I just didn’t want to do it
It works the following way: The div-container, which represents the slider, has a child (another div), which overflows over it’s parent. Basically, the child can not be seen (by setting the style-attribute to certain values - this took me a bit to make sure that IE, Firefox, Opera and Safari are happy…), but the scrollbar appears. The child’s width decides, how “thin the handle is” / how many values can be accessed. The current value is calculated with the parent-div’s scrollLeft variable (and vice versa, the setValue method also uses this variable).
The syntax is as follows:
new ScrollSlider (slider, args, noInitScroll)
slideris either the ID of adiv-element or a reference to oneargsis an Object, which can contain the following elements:min: the smallest value (default: 0)max: the largest value (default: 100)value: the current value (default: 0)size: the size (width) of the scrollbar (default: 150)scroll: the function fired when scrolled (default: function(){} [empty function])
Note that the argument passed to this function is the current value. However, all properties can be accessed viathis, e.g.this.maxorthis.value
noInitScrollis an optional Boolean; if set to true, the scroll-function will not be triggered on initialising
Example:
new ScrollSlider('slider', {
min: -42,
max: 250,
value: 100,
scroll: function (val) {
document.getElementById(’check’).innerHTML = val;
}
});
This would update $('check') everytime the ScrollSlider was changed. Since no value for size is handed over, the default is used.
Arguments can also be changed lateron, just by passing them (as a object) to the sliders’s change method. It also has the method getValue and setValue (pass an Integer).
ScrollSlider is released under GPL v3. View examples or download.

