Friday, June 21, 2013

jQuery UI: Sliders and Tooltip Values

The slider widget let's the user control a value, between a minimum and maximum by sliding a handle back and forth. This is great for forms. The developer implementing this widget, however, needs to perform some additional work in ensuring the user has appropriate feedback when the handle changes position. How else would they know what they're selecting. Even before the user starts interacting with the slider, the current value needs to be presented. In an effort to save on both development effort and on page space, the value of the slider could be displayed as a tooltip when the user moves the pointer over the handle. Further, we could have the tooltip move along with the handle as it slides, and update the value.


Here is what the modified slider widget looks like.

(function( $, undefined ) {

$.widget( "ab.slider", $.ui.slider, {

    // This new option is how the client tells the slider
    // widget it would like a tooltip to display the
    // value.
    options: {
        tooltip: false
    },

    // Constructor - if the tooltip option is false,
    // exit after calling the base constructor.
    _create: function() {

        this._super();

        if ( !this.options.tooltip ) {
            return;
        }

        // Turn the slider handle element into a tooltip.
        // Since the handle doesn't have a title attribute,
        // we have to specify the class so it knows we're
        // talking about this element, and we have to give
        // it some initial content, the value of the slider.
        // Track is turned on so the tooltip moves with the
        // mouse when the user slides the handle.
        this.handle.tooltip({
            items:   ".ui-slider-handle",
            track:   true,
            content: this._value().toString()
        });

        // Point the slide event to our private slider
        // method, used to update the tooltip content.
        this._on({
            sliderslide: "_updateTooltip"
        });

    },

    // Updates the tooltip content in response to slide
    // events.
    _updateTooltip: function( e, ui ) {

        var $handle = this.handle,
            value = ui.value.toString();

        $handle.tooltip( "option", "content", value );

    },

    // We have to make sure to destroy the tooltip widget
    // if one was created.
    _destroy: function() {

        this._super();

        if ( !this.options.tooltip ) {
            return;
        }

        this.handle.tooltip( "destroy" );

    }

});

})( jQuery );

$(function() {

    $( "#slider" ).slider({
        range:   "min",
        value:   300,
        min:     0,
        max:     900,        
        tooltip: true
    });

});

No comments :

Post a Comment