Home > Software engineering >  get handle position by the initialization
get handle position by the initialization

Time:04-05

I have the following fiddle: http://jsfiddle.net/rojq0yun/

this works great, the position of the #min div will be correctly updated when moving the slider.

Though I try to have the correct position when the slider is initalized with the default value. At the present time the handle is correctly position but the #min div not. I tried looking into the ui.handle property but it seems to be bound to the slide event :

$('#min').html(periods[ui.value])
         .position({
                          my: 'center top',
                          at: 'center bottom',
                          of: ui.handle,
                          collision: 'fit none'
                      });

Is this possible to query the position of the handle ?

edit : I query the handle object using $(this).find('.ui-slider-handle:first'); then using it as of property of position. When running it and inspecting the "left" property of the div, I get 199.4px. When moving the handle back and forth to the original position and inspecting again, the left property is then 210px. The difference is quite always 10.6px.

Where this discrepancy come from ?

updated fiddle here: http://jsfiddle.net/f4u1mphr/

CodePudding user response:

Consider the following.

https://jsfiddle.net/Twisty/2djtpakb/11/

JavaScript

$(function() {

  var periods = ["2022-01", "2022-02", "2022-03", "2022-04", "2022-05", "2022-06", "2022-07"];
  var defaultValue = 3;

  function setMin(cnt, pos) {
    $('#min')
      .html(cnt)
      .position(pos);
  }

  $("#slider").slider({
    range: "max",
    min: 0,
    max: periods.length - 1,
    step: 1,
    value: defaultValue,
    slide: function(event, ui) {
      // wait for the ui.handle to set its position
      setTimeout(function() {
        setMin(periods[ui.value], {
          my: 'center top',
          at: 'center bottom',
          of: ui.handle,
          collision: 'fit none'
        });
      }, 1);
    }
  });

  setMin(periods[defaultValue], {
    my: 'center top',
    at: 'center bottom',
    of: $("#slider .ui-slider-handle")
  });
});

Just cleaned up a bit and moved the handling of the Value to a function for ease of assignment.

  • Related