Goose
Goose

Reputation: 4821

HTML range type input enforced minimum without changing start of the range

I want to enforce minimum of 50 on a range input, but still have the range visually start at 0, so that when the input is set to 50, the slider is in the middle and the user is unable to push the slider lower.

To put the problem another way, I want the value to be 50, I want the slider to be in the middle, and I want the user to not be allowed to decrease the slider.

When I use this, the slider is at the far left, and when the slider is in the middle, it represents 75. This is not the behavior I am looking for.

<input type="range" min="50" max="100" value="50"/>

How can I enforce a minimum value on a range input without setting the start of the range as the minimum?

Upvotes: 0

Views: 1349

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65873

You'll have to have the range control set to allow a minimum of zero, but then via JavaScript reset that to 50 when the user tries to go below it.

NOTE that the input event is not universally supported on range elements, so you'll need to set up the same function in a change event handler as well.

var slider = document.getElementById("slider");
var output = document.getElementById("output");

// Set up an event handler for when the slider is changed
// To accomodate all browsers (IE), two events need to be set up.
slider.addEventListener("input", fixSlider);
slider.addEventListener("change", fixSlider);

function fixSlider(evt){
  // If the value goes below 50, reset it to 50
  if(parseInt(this.value,10) < 50){
    this.value = 50;
  }
  output.textContent = this.value;
}
<input type="range" min="0" max="100" value="50" id="slider"><span id="output">50</span>

Upvotes: 2

falinsky
falinsky

Reputation: 7438

You set current value to be equal to minimum value - so it looks like that you have range start equals to 0 but actually it's indeed 50.

Upvotes: 0

Related Questions