How to change image size with slider?

2.7k views Asked by At

I have this bit of code and I was wondering if it is possible to change the size of the image just by moving the slider:

<div class="slidecontainer">
  <input type="range" min="1" max="20" value="1" class="slider" id="Slider">
</div>
<img src="https://upload.wikimedia.org/wikipedia/commons/8/85/Elon_Musk_Royal_Society_%28crop1%29.jpg" id="Elon">

Can anyone help pls?

4

There are 4 answers

0
Sifat Haque On BEST ANSWER

You can add an eventListener to the range and then apply your logic there to change the dimension of the image.

const slider = document.getElementById('Slider');
slider.addEventListener('input', handleChange);


function handleChange(e) {
  const img = document.getElementById("Elon");
  const {value, max} = e.target;
  img.style.width = `${value*max}px`;
  img.style.height = `${value*max}px`;
}
<div class="slidecontainer">
  <input type="range" min="1" max="20" value="1" class="slider" id="Slider">
</div>
<img src="https://upload.wikimedia.org/wikipedia/commons/8/85/Elon_Musk_Royal_Society_%28crop1%29.jpg" id="Elon">

0
fonzane On

Something like:

document.getElementById("Slider").addEventlistener("change", (value) => {
  let image = document.getElementById("Elon");
  image.style.width = value;
  image.style.height = value;
});

Notice, this is just a sketch and will prob not work if u just copy and paste it.

0
kiranvj On

Change img width on slider change. Something like below

const sliderElem = document.getElementById('Slider');
const imageElem = document.getElementById('image');

function sliderChange() {
  const width = image.getAttribute('width');
  image.setAttribute("width", Number(width) + Number(sliderElem.value));

}
<div class="slidecontainer">
  <input onChange="sliderChange()" type="range" min="1" max="20" value="1" class="slider" id="Slider">
</div>
<img id="image" width="150" src="https://upload.wikimedia.org/wikipedia/commons/8/85/Elon_Musk_Royal_Society_%28crop1%29.jpg" id="Elon">

0
AudioBubble On

You need to use some javascript for this Here is the code you can run and see it. If you want more zoom then instead of x*10 write 20 or 30 according to your choice.

document.getElementById("Slider").oninput = function changeImageSize(){
         var x = document.getElementById("Slider").value;
         document.getElementById("Elon").style.height=String(x*10) + "px";
        }
<div class="slidecontainer">
        <input type="range" min="1" max="20" value="1" class="slider" id="Slider">
      </div>
      <img src="https://upload.wikimedia.org/wikipedia/commons/8/85/Elon_Musk_Royal_Society_%28crop1%29.jpg" id="Elon">