I'm have a slider that goes from 1 - 3, I'd like my image src to change depending on what the slider is set to. I've tried to do this using an else if statement but it doesn't seem to be changing?
HTML
<span id="valBox"></span>
<input type="range" min="1" max="3" step="1">
<img id="demo" src="default-image.png">
Javascript
<script>
if (step === 1) {
document.querySelector("input.step").innerHTML.src = "one-image.png";
} else if (step === 2) {
document.querySelector("input.step").innerHTML.src = "two-image.png";
} else if (step === 3) {
document.querySelector("input.step").innerHTML.src = "three-image.png";
};
</script
CodePudding user response:
You need to run your JavaScript in an onchange
event handler.
const imageElement = document.getElementById("demo");
const selectorElement = document.getElementById("selector");
selectorElement.onchange = () => {
const step = selectorElement.valueAsNumber;
if (step === 1) {
imageElement.src = "one-image.png";
} else if (step === 2) {
imageElement.src = "two-image.png";
} else if (step === 3) {
imageElement.src = "three-image.png";
}
}
<span id="valBox"></span>
<input id="selector" type="range" min="1" max="3" step="1">
<img id="demo" src="default-image.png">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>