Display value of HTML range slider using JS
P粉988025835
P粉988025835 2023-09-13 00:42:58
0
1
625

The JS used to display the HTML range slider value works fine for the first item (A1). However, I also want to use it for A2 projects (actually there are 20 projects, so it needs to be reused 19 times). Is there a way to code for multiple iterations?

 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");
      });
<body>
<div class="itemstatement">A1. Blah Blah Blah.</div>
<div class="range">
<div class="sliderValue"><span>0</span></div>
<div class="field">
<div class="value left">0</div>
<input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1">
<div class="value right">10</div>
</div></div>

<div class="itemstatement">A2. Blah Blah Blah.</div>
<div class="range">
<div class="sliderValue"><span>0</span></div>
<div class="field">
<div class="value left">0</div>
<input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1">
<div class="value right">10</div>
</div></div></div></body>

P粉988025835
P粉988025835

reply all(1)
P粉680000555

Of course. You'll easily recognize your own code, which is 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 class="itemstatement">A1. Blah Blah Blah.</div>
<div class="range">
  <div class="sliderValue"><span>0</span></div>
  <div class="field">
    <div class="value left">0</div>
    <input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1">
    <div class="value right">10</div>
  </div>
</div>

<div class="itemstatement">A2. Blah Blah Blah.</div>
<div class="range">
  <div class="sliderValue"><span>0</span></div>
  <div class="field">
    <div class="value left">0</div>
    <input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1">
    <div class="value right">10</div>
  </div>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template