Custom Slider Value Display with jQuery UI

Tuesday, March 27, 2012

The jQuery UI slider widget doesn't display it's current value by default. However, you can tap into the slide event and grab the current value from the second parameter passed to the event handler. The second parameter in a jQuery UI event handler is typically named ui, and always contains some useful information about the state of the widget.

$(function () {
    var ageInput = $("#ageInput");
    var ageDisplay = $("#ageInput > div");

    var updateSliderValue = function (event, ui) {
        ageDisplay.text(ui.value);
    };

    ageInput.slider({
        min: 0, max: 122,
        slide: updateSliderValue
    });        
});

You can also position the display of the value above the slider handle / thumb. The DOM element representing the slider thumb is passed in the ui parameter as the handle property.

var updateSliderValue = function (event, ui) {
    ageDisplay.text(ui.value)
              .css($(ui.handle).position());
};

Having the value display immediately (before the user starts dragging and the slide event fires) is a bit trickier. A complete example with one possible solution is available on jsFiddle.


Comments
gravatar Jared Roberts Tuesday, March 27, 2012
I wrote something similar a long while ago that may help others. Nice work Scott. weblogs.asp.net/...
gravatar Elijah Manor Tuesday, March 27, 2012
Nice tip. I've also done something similar but used the handle to store the value... like this http://jsfiddle.net/elijahmanor/dLq5B/
gravatar Matt Saturday, March 31, 2012
There's a nifty plugin for this type of slider, too.

Matt Saturday, March 31, 2012
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!