Search code examples
javascripthtmlcsswidthaddeventlistener

Change width of DiV element using range slider and JavaScript


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Range Slider Width</title>
<script src="slajder.js"></script>
<style>
  #ekran {
      width: 80px;
      height: 100px;
      background-color: pink;
  }
</style>
</head>
<body>
    <input type='range' min="1" max="400" value="150">
    <div id='ekran'></div>
</body>
</html>

Without ID on input range slider with only id on DIV element i needed to write JS code so when i move slider acording to a value of a slider width of that DIV element with ID ='ekran' is chaning too. (with a slider of course). Im not sure if CSS is correct but i had something like this on exam. Please help guys. I beginer in JS. Learning it still and i have a looooot more to learn.

PS: if value of range slider is '30' width of that div will be 30px. thats all


Solution

  • you can get the value of the slider with from the input event from the slider like this

    e.target.value
    

    and set that to the width of the div

    let slider = document.querySelector('[type=range]')
    let div = document.querySelector('#ekran')
    
    slider.addEventListener('input', e => {
      div.style.width = e.target.value + 'px'
    })
    #ekran {
      width: 80px;
      height: 100px;
      background-color: pink;
    }
    <input type='range' min="1" max="400" value="80">
    <div id='ekran'></div>