Reputation: 21
im working on a slider in html, that will show different images depending on the slider value.
so if the slider is set to value 1, image1.jpg is shown, value 2 will show image2.jpg and so on.
I have found the slider part on w3schools and has managed to output new images to it. link to w3schools slider
But i dont know how to refresh the images, for now the code just prints a new one by the olds images side. i++
does anyone know how to refresh image, instead of printing a one new every time.
Any help would be appreciated!
var slider = document.getElementById("myRange");
var output = document.getElementById("value");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
var x = document.createElement("IMG");
x.setAttribute("src", "image" + this.value + ".jpg");
document.body.appendChild(x);
}
<div class="slidecontainer">
<input type="range" min="1" max="2" value="1" class="slider" id="myRange">
<p>Value: <span id="value"></span></p>
</div>
Upvotes: 1
Views: 547
Reputation: 12078
You can just use the img
element with the default image or src
value:
var slider = document.getElementById("myRange");
var output = document.getElementById("value");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
var img = document.getElementById("img");
img.setAttribute("src", "https://loremflickr.com/320/240/" + this.value);
}
<div class="slidecontainer">
<input type="range" min="1" max="5" value="1" class="slider" id="myRange">
<p>Value: <span id="value"></span></p>
<img src="https://loremflickr.com/320/240/1" alt="" id="img">
</div>
Upvotes: 1