I am working on a web page that has multiple (8) input sliders on the same page. I found a script that works for one slider using document.getElementById. Since I’ll need ID’s for all 8 sliders, I’m not sure how to alter this code to accommodate all 8.
Bottom line, is there a way to have multiple ID’s in the same script?
Here’s my html:
<div class="range-wrap">
<input id="range" type="range" name="range" min="3" max="20" value="12" step="1" class="slider">
<p id="display" style="text-align:center;margin-top:30px;"></p>
<p id="numVal" style="text-align:center;color:#f1f1f1;"></p>
</div>
Here’s my JavaScript:
var slider = document.getElementById("range");
var display = document.getElementById("display");
var getVal = slider.value;
numVal.innerHTML = getVal; // If you don't want the number to be displayed, delete this. This is to show at which number the label will change
if(getVal<7) {
display.innerHTML = "Need Help";
}
if(getVal>=7 && getVal<=15) {
display.innerHTML = "Mediocre";
}
if(getVal>20){
display.innerHTML = "Doing Great";
}
slider.oninput = function() {
numVal.innerHTML = this.value;// If you don't want the number to be displayed, delete this. This is to show at which number the label will change
var getVal = this.value;
if(getVal<5) {
display.innerHTML = "Need Help";
}
if(getVal>=7 && getVal<=10) {
display.innerHTML = "Mediocre";
}
if(getVal>15){
display.innerHTML = "Doing Great";
}
}
I tried changing getElementById to getElementsByClassName and assigning each element a class, but it broke the script.
I am not an experienced JS coder.
2
Answers
To handle multiple sliders on the same page, you can use classes instead of IDs:
Afterwards, you can access all
input
elements with classslider
by using getElementsByClassName:You can use
document.querySelectorAll
to select all the sliders on the page and then loop through them to add event listeners. Here’s an example of how you could do it:This way, you can have multiple sliders on the same page and update their displays independently without having to write separate code for each slider.