Search code examples
jqueryjquery-uisliderposition

jQuery UI slider labels - follow handles on resize


I'm using labels to display handle values with jQuery UI slider.

How can I maintain the position of these values on resize?

Here's a fiddle: http://jsfiddle.net/kirkbross/vc8tumg9/3/

$(label).html(hours + ':' + minutes).position({
my: 'top center',
at: 'bottom center',
of: ui.handle,
offset: "0, 30"
});

For extra credit... can you tell me why my initial values aren't displaying in the correct position (as on slide)?

For double extra credit... can you tell me how to bind slide to the label in addition to the handle?


Solution

  • You could just add a label using css... the only major issue is getting an initial value added as the create event does not provide the ui variable (demo):

    CSS

    /* Add tooltips to slider handles */
     .ui-slider-handle:after {
        content : attr(data-value);
        position: absolute;
        bottom: 30px;
        left: -24px;
        min-width: 60px;
        height: 12px;
        background-color: #eee;
        -webkit-border-radius: 3px;
        border-radius: 3px;
        border: #ddd 1px solid;
        color: #333;
        font: .7em/1em Arial, Sans-Serif;
        padding: 1px;
        text-align: center;
    }
    .ui-slider-handle:before {
        content:"";
        position: absolute;
        width: 0;
        height: 0;
        border-top: 8px solid #eee;
        border-left: 8px solid transparent;
        border-right: 8px solid transparent;
        top: -8px;
        left: 50%;
        margin-left: -8px;
        margin-top: -1px;
    }
    

    Script

    var initialValues = [180, 330, 1080, 1320],
        updateValue = function (ui) {
        var hours = Math.floor(ui.value / 60);
        var minutes = ui.value - (hours * 60);
    
        if (hours.length == 1) hours = '0' + hours;
        if (minutes.length == 1) minutes = '0' + minutes;
        if (minutes == 0) minutes = '00';
        if (hours >= 12) {
            if (hours == 12) {
                hours = hours;
                minutes = minutes + " PM";
            } else {
                hours = hours - 12;
                minutes = minutes + " PM";
            }
        } else {
            hours = hours;
            minutes = minutes + " AM";
        }
        if (hours == 0) {
            hours = 12;
            minutes = minutes;
        }
        $(ui.handle).attr('data-value', hours + ':' + minutes);
    };
    
    $(".pct-slider").slider({
        min: 0,
        max: 1440,
        step: 15,
        range: false,
        values: initialValues,
        create: function (event, ui) {
            $.each( initialValues, function(i, v){
                updateValue({
                    value: v,
                    handle: $('.ui-slider-handle').eq(i) 
                });
            });
        },
        slide: function (event, ui) {
            updateValue(ui);
        }
    });