Search code examples
javascripthtmlinputlabel

How to make a <label> text enable or disable an <input> range?


I would like the range to toggle itself (minimum / maximum) when I click on the label. Is that possible with only HTML or CSS ? Do I need some JS?

I have the following code :

<label>
        This is the label text
        <input type="range" min="0" max="1" step="0.01" value="1" />
</label>

Code : https://jsfiddle.net/gjxf60s8/


Solution

    1. Remove the step attribute
    <label>
            This is the label text
            <input type="range" min="0" max="1" step="0.01" value="1" />
    </label>
    
    1. Try this new js code
    document.addEventListener('DOMContentLoaded', function() {
      var label = document.querySelector('label');
      var rangeInput = document.querySelector('input[type="range"]');
    
      label.addEventListener('click', function() {
        // Toggle between min and max values
        if (rangeInput.value > rangeInput.max) {
          rangeInput.value = rangeInput.min;
        } else {
          rangeInput.value = rangeInput.max;
        }
      });
    });
    
    1. Is implemented here https://jsfiddle.net/tzko8hse/3 (Clicking changes the value to the maximum or minimum defined on the label.)