javascripthtmlcsspls

How to change image size with slider?


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?


Solution

  • 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">