I’m pretty new to JavaScript so I’ve been messing around and teaching myself how to use the functions. I’m trying to use setInterval to make a function that constantly changes the size of the thumb based on the value of the slider.
I tried to use getElementById and other things and I can’t figure it out.
Here is the HTML:
<input type="range" class="javaRange" id="rangeInput2" name="rangeInput2" min="0" max="1000" value="0"
oninput="amount2.value=rangeInput2.value">
<output id="amount2" name="amount2" for="rangeInput2">0</output>
Here is the CSS (The slider is customized):
<style>
.javaRange {
-webkit-appearance: none;
background-color: #cdfffe;
height: 20px;
overflow: visible;
width: 400px;
border-radius: 50px;
}
.javaRange::-webkit-slider-thumb {
-webkit-appearance: none;
background: #00918f;
border-radius: 50%;
cursor: pointer;
height: 20px;
width: 20px;
border: 0;
}
</style>
and here is the JavaScript that I have currently:
<script>
const constant = 0.12;
const thumbValue = document.getElementById("rangeInput2").value;
function thumbSize(){
document.getElementById("rangeInput2").style.width = 20 + parseInt(thumbValue) + "px";
document.getElementById("rangeInput2").style.height = 20 + parseInt(thumbValue) + "px";
};
setInterval(thumbSize());
</script>
I’ve tried so many things. please help!
EDIT:
I just got an answer that really helped but it raised another question. am I able to specifically target thumb size? Here is the line of code I’m using:
document.getElementById("rangeInput2").style.width = 20 + parseInt(thumbValue) + "px";
It worked except that it was changing the size of the entire slider, and I only wanted to change the size of the thumb.
2
Answers
You don’t need to use
setInterval
; just callthumbSize()
in thatoninput
handler.Using
setInterval
most certainly isnt the best solution here, however its not the reason it doesnt work. There’s at least 2 reasons it wont work here:setInterval
expects the first parameter to be a function. Your code reads:setInterval(thumbSize());
Which takes the result of thethumbSize
function and sends that tosetInterval
. What you actually want issetInterval(thumbSize)
.You can simply move the
thumbValue
inside the function to fix that.There may be other problems but those are 2 definite issues.
Please dont do this for real code you plan on shipping to someone. The correct answer is to listen for the value changing and react to that. But for playing around with code its certainly a "reasonable" approach