-2

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
  • care to give more detail about what you need? what do you mean by "toogle itself?" and what have you tried? Commented Nov 14, 2023 at 18:54
  • The idea is flawed from the start. The main issue is, that a label is a semantic tag that give assistance to a user, and screen-readers. A focus and a click on a label will also directly select affect the input by default. changing the default behavior will cause the loss of UX and accessibility. If you want to switch the min and max values with each other, you should include a toggle on its own. Commented Nov 15, 2023 at 6:31

2 Answers 2

-1
  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.)
Sign up to request clarification or add additional context in comments.

Comments

-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');
    }
  });
});

2 Comments

Thank you for your answer but I think I wasn't very clear in my question. I didn't want to change the minimum and maximum, I wanted the value to toggle between minimum and maximum when I click on the label. Using your code as base, here is what worked : jsfiddle.net/v1ausztf
try the new code in the new answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.