Home > Back-end >  HTML Range Slider w/ JS to Display Value
HTML Range Slider w/ JS to Display Value

Time:11-19

The JS being used to display the value of an HTML range slider is working fine for the first item (A1). However, I want to use it for item A2 too (and there are actually 20 items, so it needs to be used over and over 19 more times). Is there a way to write the code for multiple iterations?

`

<body>
<div >A1. Blah Blah Blah.</div>
<div >
<div ><span>0</span></div>
<div >
<div >0</div>
<input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1">
<div >10</div>
</div></div>

<div >A2. Blah Blah Blah.</div>
<div >
<div ><span>0</span></div>
<div >
<div >0</div>
<input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1">
<div >10</div>
</div></div></div>
        
<script>
      const slideValue = document.querySelector("span");
      const inputSlider = document.querySelector("input");
      inputSlider.oninput = (()=>{
        let value = inputSlider.value;
        slideValue.textContent = value;
        slideValue.style.left = (value/.1)   "%";
        slideValue.classList.add("show");
      });
      inputSlider.onblur = (()=>{
        slideValue.classList.remove("show");
      });
        
</script>
</body>

``

CodePudding user response:

Surely there is. You will easily recognize your own code, wrapped inside a for loop.

var elems = document.querySelectorAll(".range");
elems.forEach(function(elem) {
  const slideValue = elem.querySelector("span");
  const inputSlider = elem.querySelector("input");
  inputSlider.oninput = (() => {
    let value = inputSlider.value;
    slideValue.textContent = value;
    slideValue.style.left = (value / .1)   "%";
    slideValue.classList.add("show");
  });
  inputSlider.onblur = (() => {
    slideValue.classList.remove("show");
  });
})
<div >A1. Blah Blah Blah.</div>
<div >
  <div ><span>0</span></div>
  <div >
    <div >0</div>
    <input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1">
    <div >10</div>
  </div>
</div>

<div >A2. Blah Blah Blah.</div>
<div >
  <div ><span>0</span></div>
  <div >
    <div >0</div>
    <input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1">
    <div >10</div>
  </div>
</div>

  • Related