Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript to scroll iframe up and down

Tags:

jquery

key

iframe

Is it possible to scroll the iframe window from the parent window using keys or javascript? The iframe content is from another domain, different from the parent window.

like image 425
Mickey Cheong Avatar asked Nov 01 '09 08:11

Mickey Cheong


People also ask

Can JavaScript access iframe content?

You could use . contents() method of jQuery. The . contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

How do I enable scrolling in iframe?

1) Set the scrolling attribute of the iframe to no (scrolling="no"). This will disable both horizontal and vertical scroll bars. 2) Set the width attribute of the iframe to 200% (width="200%"). This will enable only the horizontal scroll bar.


1 Answers

Since the iframe content is from another domain, you will not be able to alter it's DOM due to security reasons.

Although you can scroll it by using the arrow keys, when you have it activated. At least it works for me in Chrome and Firefox.

If you want to be able to scroll it from javascript, I would suggest the following approach. (it assumes you know the width and height of the iframe content and your iframe). Basically let a div in your DOM take care of scrolling.

<a href="#" id="scroll">Scroll to (400,400)!</a><br />

<div id="google" style="width: 300px; height: 200px; overflow: auto;">
   <iframe width="800" height="600" src="http://www.google.com/" scrolling="no">
   </iframe>
</div>

<script type="text/javascript">
$("#scroll").click(function()
{
  $("#google").scrollTop(400).scrollLeft(400);
  return false;
});
</script>

For smoother scrolling of the div you could try the code from this article.

like image 116
Martin Nycander Avatar answered Dec 04 '22 13:12

Martin Nycander