1

I would like to scroll the content of the iframe to the middle of the page automatically. This is the script:

<iframe src="<?php echo $redLink; ?>" width="300" height="155" frameborder="0">
  <p>Your browser does not support iframes.</p>
</iframe>

How can I do that?

Mike Z
  • 4,121
  • 2
  • 31
  • 53
Ido Bukin
  • 51
  • 1
  • 2
  • 6

2 Answers2

0

With jQuery it would be

var middle =  (($('iframe').height()) / 2);
$('iframe').scrollTop(middle);
loveNoHate
  • 1,549
  • 13
  • 21
  • `$('iframe').height()` returns the height of the iframe, not it's contents. So this won't scroll to the middle – Bill Aug 13 '15 at 11:02
  • Who, what, where? I cannot understand the question actually anymore! To `scroll the content of the iframe to the middle of the page automatically` the `iFrame` has to be bigger than the page. jQuery is not asked here anyway. %)P However, this scrolls the page to the middle of the `iFrame`, assumed the `iFrame` is on the top of the page! – loveNoHate Aug 15 '15 at 14:13
  • I think the question is asking that the iframe is scrolled to the middle of it's content - which isn't possible cross-domain – Bill Aug 17 '15 at 09:02
0

I went to w3c.org using latest FF, Chrome and IE9 and threw the following into the JS console (it worked in all three).

var fr = document.createElement("iframe");
fr.src = "http://w3c.org";
fr.onload = function() {
    var de = (this.contentDocument||this.contentWindow.document).documentElement;
    var bd = de.getElementsByTagName("body")[0];
    de.scrollTop = bd.scrollTop = Math.floor(bd.scrollHeight / 2);
}
document.body.appendChild(fr);

So all you need is to add the onload function to your markup

onload="(function() {
    var de = (this.contentDocument||this.contentWindow.document).documentElement;
    var bd = de.getElementsByTagName('body')[0];
    de.scrollTop = bd.scrollTop = Math.floor(bd.scrollHeight / 2);
})()"
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
  • My console shows `Uncaught TypeError: Cannot read property 'document' of undefined` using this snippet – Bill Aug 13 '15 at 11:01
  • Also, `this` would refer to the global window variable, not the iframe. – Bill Aug 13 '15 at 11:12