skip to Main Content

so this slider changes the width of the iframe and I tried to add another slider to change the height of the iframe but I didn’t know what the JavaScript should be for that. So my question is how can we add another slider that can change the height of the iframe, what should the JavaScript be? This is the HTML and the JS:

let slider = document.querySelector('[type=range]')
let div = document.querySelector('#myIframe')

slider.addEventListener('input', e => {
  div.style.width = e.target.value + 'px'
})
<iframe id="myIframe"></iframe>

<input type="range" min="240" max="1024" value="240" style="width:100%">

2

Answers


  1. Here is a CSS alternative

    iframe {
      height: 140px;
      width: 240px;
      resize: both
    }
    <iframe id="myIframe"></iframe>

    but if you insist, just add one for the height.

    I suggest to delegate from a static container

    const iFrame = document.querySelector('#myIframe');
    
    const sliders = document.getElementById('sliders');
    const w = document.getElementById('w');
    const h = document.getElementById('h');
    sliders.addEventListener('input', e => {
      const tgt = e.target.closest('[type=range]');
      if (!tgt) return; // not a slider
      iFrame.style.width = w.value + 'px'
      iFrame.style.height = h.value + 'px'
    })
    iframe {
      height: 140px;
      width: 240px;
    }
    <iframe id="myIframe"></iframe>
    
    <div id="sliders">
      <label>width: <input type="range" id="w" min="240" max="1024" value="240" style="width:100%" /></label>
      <label>height: <input type="range" id="h" min="140" max="1024" value="140" style="width:100%" /></label>
    </div>
    Login or Signup to reply.
  2. You can add id for every slider, then query the elements:

    <!DOCTYPE html>
    <html>
    <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">
    </head>
    <body>
      <iframe id="myIframe"></iframe>
      <input id="widthSlider" type="range" min="240" max="1024" value="240" style="width:100%">
      <input id="heightSlider" type="range" min="240" max="1024" value="240" style="width:100%">
      <script>
        let widthSlider = document.querySelector('#widthSlider')
        let heightSlider = document.querySelector('#heightSlider')
        let iframe = document.querySelector('#myIframe')
    
        widthSlider.addEventListener('input', e => {
          iframe.style.width = e.target.value + 'px'
        })
        heightSlider.addEventListener('input', e => {
          iframe.style.height = e.target.value + 'px'
        })
      </script>
    
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search