Scrolling an iframe Programmatically

Scrolling a div programmatically is typically very easy, with something like this:

$(‘#divid’).scrollTop(400); // scrolls to position 400 of the div vertically

So, you figure that it’s the same code for an iframe you have on your page:

$(‘iframe’).scrollTop(400);

Quickly you will discover it does not work. The iframe itself is not the container that has the scroll element associated with it. Instead, you can use a jquery method “.contents()” to find the direct content of the iframe, and then scroll that. Like this:

$(‘iframe’).contents().scrollTop(400);

JQuery documentation says this: “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.” (http://api.jquery.com/contents/)

Leave a Reply