views:

4840

answers:

4

I dynamically load an iframe with javascript. After it's loaded, how can I make it scroll down a specific number of pixels (ie. after the page in the iframe has loaded, how can I make the iframe scroll by itself to the a specified region of the page?)

A: 

I have just done this same thing with a div, I am sure you can adapt it for an iFrame.

Have a look at this, you will see the div scroll down, view the source and look at line 680 onwards

Rippo
+1  A: 

Use the scrollTop property of the frame's content to set the content's vertical scroll-offset to a specific number of pixels (like 100):

<iframe src="foo.html" onload="this.contentWindow.document.documentElement.scrollTop=100"></iframe>
Justin Ludwig
+5  A: 

You can use the onload event to detect when the iframe has finished loading, and there you can use the scrollTo function on the contentWindow of the iframe, to scroll to a defined position of pixels, from left and top (x, y):

var myIframe = document.getElementById('iframe');
myIframe.onload = function () {
    myIframe.contentWindow.scrollTo(xcoord,ycoord);
}

You can check a working example here.

Note: This will work if both pages reside on the same domain.

CMS
So if the pages are not on the same domain, this will not work?
Chief17
@Chief17 - that's right, it would violate the same domain policy for Javascript.
Steve Claridge
A: 

A jQuery solution:

$("#frame1").ready( function() {

  $("#frame1").contents().scrollTop( $("#frame1").contents().scrollTop() + 10 );

});
Steve Claridge