Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scroll an iframe from parent page

I have created two webpages, one contains the other in an iframe. I would like to scroll the embedded page from the parent page via javascript.

What I have tried so far:

  1. $('#go').scrollTop(200);

  2. $('.footer').scrollTop(200);

  3. var frame = document.getElementById('go');
    frame.contentWindow.scrollTo(0, 200);

none of these have worked

the parent webpage html:

<html>
<body>
.
.
.
<div class="footer">
        <iframe id="go" src="go.html"></iframe>
    </div>
     </body>
</html>

Both of these webpages are local files on the computer and I am using Google chrome with "--allow-file-access-from-files" flag.

How do I scroll the iframe to a certain position?

like image 518
stackErr Avatar asked May 29 '13 19:05

stackErr


People also ask

How do I scroll with an iframe?

To scroll an iframe with JavaScript, we can use the scrollTo method. const myIframe = document. getElementById("iframe"); myIframe. onload = () => { myIframe.


Video Answer


2 Answers

This works:

document.getElementById("go").contentWindow.setTimeout("this.scrollTo(0, 200);",1);

Update. Doh. Works in IE only, but I think there's something there.

Update 2 This works universally:

document.getElementById("go").onload = function () { this.contentWindow.scrollTo(0, 200) };

You have to wait for iframe content to finish loading for scrollTo to work.

like image 54
Yuriy Galanter Avatar answered Oct 04 '22 03:10

Yuriy Galanter


You can use window.postMessage to send a message from your parent frame to the iframe, telling it to scroll. This takes you setting-up a postMessage script in the parent frame and a receiveMessage script in the iframe. It's the receiveMessage code that would actually scroll the iframe.

I've used this polyfill quite successfully: http://benalman.com/projects/jquery-postmessage-plugin/

like image 41
Jasper Avatar answered Oct 04 '22 02:10

Jasper