Question

I've build a slider with the value inside the handle.

How can I manipulate the movement, that the handle at "4 years" is in the middle and at "5 years" is positioned inside the blue box?

http://jsbin.com/IGEsIJaQ/6/edit

Was it helpful?

Solution

You can use margin-left

Example:

$(function() {
  var slider = $('#slider').slider({
        range: 'min',
        min: 3,
        max: 5,
        value:3,

        create: function(event, ui) {
          var v= $(this).slider('value');

          $(this).find('.ui-slider-handle').text(v + ' years');

        },

        slide: function( event, ui) {
          var handle = $( '.ui-slider-handle' ),
              handleWidth = handle.width(),
              position = handle.position(),
              marginLeft;

          handle.text(ui.value + ' years');
          if(ui.value == 4)
            marginLeft = -handleWidth/2-10;
          else if(ui.value == 5)
            marginLeft = -handleWidth-20;
          else
            marginLeft = 0;
          handle.css('margin-left',marginLeft+'px');
        }
    });
});

http://jsbin.com/IGEsIJaQ/8/edit?html,css,js,output

OTHER TIPS

If you have multiple sliders, or a range slider with two handles:

$(function() {
      var your_slider = $('#slider').slider({
        range: 'min',
        min: 3,
        max: 5,
        value:3,

        create: function(event, ui) {
            var v= $(this).slider('value');

            $(this).find('.ui-slider-handle').text(v + ' years');

        },

        slide: function(event, ui) {
            $(ui.handle).text(ui.value + ' years');

            var handleWidth = $(ui.handle).width(),
                position = $(ui.handle).position(),
                marginLeft;

            if(ui.value == your_slider.slider( "option", "min" ))
                marginLeft = 0;
            else if(ui.value == your_slider.slider( "option", "max" ))
                marginLeft = -handleWidth;
            else
                marginLeft = -handleWidth/2;

            $(ui.handle).css('margin-left',marginLeft+'px');
        }
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top