Search code examples
htmljqueryrangeslider

How to restrict HTML range slider from moving beyond a range


I'm using a range slider with range 0 to 100 and the current value is set to max.

My objective is that I have a limiting value of 50 so that the slider could be moved between 50 and 100 and not 0 to 50. I have setup a jQuery handler as below, however I'm still able to move backwards from 50.

Is there a way to prevent the slider from going backwards from 50?

$(document).on("input change", "#range", function() {
  var scrolled_value = $(this).val();
  var limiting_value = 50;

  if (scrolled_value <= limitng_value)
    return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="range" type="range" name="range" min="0" value="100" max="100" />


Solution

  • You can set the value in the change event to stop it going below that value:

      if (scrolled_value <= limiting_value)
        $(this).val(limiting_value);
    

    Giving an updated snippet (with as few changes as possible to the original):

    $(document).on("input change", "#range", function() {
      var scrolled_value = $(this).val();
      var limiting_value = 50;
    
      if (scrolled_value <= limiting_value)
        $(this).val(limiting_value);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input id="range" type="range" name="range" min="0" value="100" max="100" />