skip to Main Content

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/

2

Answers


  1. You need to use js.

    Try this 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.getAttribute('min') === '0') {
          rangeInput.setAttribute('min', '1');
          rangeInput.setAttribute('max', '100');
        } else {
          rangeInput.setAttribute('min', '0');
          rangeInput.setAttribute('max', '1');
        }
      });
    });
    
    Login or Signup to reply.
    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.)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search