Home > Back-end >  How to restrict HTML range slider from moving beyond a range
How to restrict HTML range slider from moving beyond a range

Time:11-16

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" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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" />
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can solve this issue by setting the sliders value to 50 when it's below 50, like shown below:

const input = document.querySelector("input");
const sliderLimit = 50;


input.addEventListener("input", () => {
  if (input.value < sliderLimit)
    input.value = sliderLimit;
})
<input type="range" min="0" value="100" max="100" />
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Minimal solution using jQuery (like OP) while also limiting the value on first-render

$('input').on("input change", function() {
  if (this.value > 50 )
    this.value = 50
}).trigger('change')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="range" min="0" value="100" max="100" />
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

By the way, I've created a beautiful CSS-only range slider: https://github.com/yairEO/ui-range

  • Related