Scroll to iframe using buttons and Javascript

0

Good, on my page I have an iframe and on top of this 3 buttons, one to do Scroll Up, another Scroll Down and another to pause the Scroll.

 <html>
      <head>
       <script>

        function scrollAbajo(){
            var myIframe=document.getElementById('iframe');
            myIframe.contentWindow.scrollTo(0,500);
        }
    </script>
</head>
<body>
    <input type="button" name="subir" value="Subir"/>
    <input type="button" name="bajar" value="Bajar" onclick="scrollAbajo()"/>
    <input type="button" name="pausa" value="Pausa"/>
    <br>
    <iframe src="http://www.w3schools.com" id="iframe">
    </iframe>
</body>

This is my code, and I have to say it's the first time I've worked with things like that and the truth is that I can not make it work. So far I have done the function to make it go down, and then with that, continue with the rest, but nothing at all.

    
asked by NeoChiri 19.11.2016 в 15:37
source

1 answer

2

The problem with that solution is that, due to browser security restrictions, it would only work on frames that point to the same domain. Otherwise you will get an error like this:

VM307:6 Uncaught DOMException: Blocked a frame with origin "http://null.jsbin.com" from accessing a cross-origin frame.
    at scrollAbajo (<anonymous>:6:35)
    at HTMLInputElement.onclick (http://null.jsbin.com/runner:1:659)scrollAbajo @ VM307:6onclick @ VM218 runner:1

Another solution is that you insert the iframe inside a div and you control the scroll of the div:

#div_iframe {
  border-style: inset;
  border-color: grey;
  overflow: scroll;
  height: 500px;
  width: 90%
}

#frame {
  width: 100%;
  height: 1000%;
}
 <html>
      <head>
       <script>

        function scrollAbajo(){
            document.getElementById('div_iframe').scrollTop = 500
        }
        function scrollArriba(){
            document.getElementById('div_iframe').scrollTop = 0
        }
    </script>
</head>
<body>
  <input type="button" name="subir" value="Subir" onclick="scrollArriba()"/>
  <input type="button" name="bajar" value="Bajar" onclick="scrollAbajo()"/>
  <input type="button" name="pausa" value="Pausa"/>
  <div id='div_iframe'>
    <iframe id='frame' src='http://www.w3schools.com' />
  </div>
</body>
    
answered by 19.11.2016 / 22:09
source