Home > other >  How to make jquery .range() slider fire only when the cursor / finger is released?
How to make jquery .range() slider fire only when the cursor / finger is released?

Time:08-07

I am using a jquery slider for selecting the age range. It has a minimum and maximum value from either ends. When the slider is dragged from any side whether left or right, it continuously fires N number of AJAX calls (as shown in the Network tab of browser's Inspect Element) till it is being dragged and stops only when the slider is released. Keep dragging and it will keep firing the AJAX calls non stop. This makes the code update the database in the backend N number of times for a single selection. However, my requirement is the exact reverse of how it is currently functioning. The AJAX call should fire only once and that too when the cursor is released from the dragger. How to accomplish this? Jquery seems to give no default option for this (please correct me if I am wrong).

HTML

<div >
  <form field="age_range">
    <div id="maxAge" min="18" max="75" minVal="<?php echo $ageRange[0]; ?>" maxVal="<?php echo $ageRange[1]; ?>"></div>
    <input type="text"  id="sliderVal" readonly>
  </form>
</div>

Jquery

$("#maxAge").slider({
  range: true,
  min: parseInt($("#maxAge").attr('min')),
  max: parseInt($("#maxAge").attr('max')),
  values: [
    parseInt($("#maxAge").attr('minVal')), 
    parseInt($("#maxAge").attr('maxVal'))
  ],
  slide: function(event, ui) {
    $.ajax({
      type: 'POST',
      url: 'processes/settings.php',
      data: 'field=age_range&value=' ui.values[0] '-' ui.values[1],
      success: function(data){
        $("#sliderVal").val($("#maxAge").slider("values", 0)   "-"   $("#maxAge").slider("values", 1));
      }
    });
  }
});
$("#sliderVal").val($("#maxAge").slider("values", 0)   "-"   $("#maxAge").slider("values", 1));

CodePudding user response:

Could you use the change event instead as that only fires once after the user stops sliding

$("#maxAge").slider({
  range: true,
  min: parseInt($("#maxAge").attr('min')),
  max: parseInt($("#maxAge").attr('max')),
  values: [
    parseInt($("#maxAge").attr('minVal')), 
    parseInt($("#maxAge").attr('maxVal'))
  ],
  change: function(event, ui) {
   
    $.ajax({
      type: 'POST',
      url: 'processes/settings.php',
      data: 'field=age_range&value=' ui.values[0] '-' ui.values[1],
      success: function(data){
      console.log('')
        $("#sliderVal").val($("#maxAge").slider("values", 0)   "-"   $("#maxAge").slider("values", 1));
      }
    });
  }
});

Hope this helps

  • Related