Monday, July 7, 2014

Connecting Sliders To Number Inputs

The input element can be configured to accept numbers. When this happens, the input is just like a regular text input, expect now it's rendered with spinner buttons — used to increment or decrement values. Further constraints can be placed on number inputs, like the minimum and maximum allowed values. This let's us do interesting things, like connect the number input to a jQuery UI slider widget.

Sliders, used in this context, are meant to assist the user in filling out the number input. The spinner buttons on the number input aren't exactly obvious, slider should fill in this gap. For example, the user has the choice of manually typing the number, as they would any other text input, or by using the slider.

It goes without saying, that as the user types, the slider should reflect the current input value and as the user slides, the input should reflect the current slider value. Here's some code.

var $input = $( '[name="percent"]' ).on({
    input: function( e ) {
        var $input = $( e.currentTarget );
        $input.next()
            .slider( 'value', $input.val() );
    }
});

$( '<div/>' ).insertAfter( $input )
    .slider({
        min: +$input.prop( 'min' ),
        max: +$input.prop( 'max' ),
        stop: function( e, ui ) {
            $input.val( ui.value );   
        }
});

The first thing this code does is setup a handler for the input event on the percent element. This event triggers whenever the input changes. So, in other words, as the user types. All the handler itself has to do is find the slider widget — the next sibling — and update the value.

Next is the slider code, where we make use of the fact that the input we're connecting to is a number input. The min and max properties are passed to the slider configuration as it's min and max allowable values. So there's a one-to-one correspondence there, in addition to just the value. The stop event handler updates the input whenever the user stops sliding.