How to make “scrollIntoView” apply to IFRAME only

Let’s say you have a really long HTML page with scrollbars, for the sake of argument something like this:

<div>aaaa</div>
<div>aaaa</div>
<div>aaaa</div>
...more content...
<div id="xB">bbbb</div>
<div>aaaa</div>
<div>aaaa</div>
<div>aaaa</div>
...much more content...

And somewhere, perhaps on pageload, you want to make sure that highlighted element is visible to the user, so to scroll it into view you execute

document.getElementById("xB").scrollIntoView();

And it works fine and well – the needed element is automatically displayed on top of the page. But what if this page is in an IFRAME and the parent page has a large scrollable content of it’s own:

<div>zzzz</div>
<div>zzzz</div>
<div>zzzz</div>
...more content...
<iframe id="xifr" width="200" height="200" src="PreviousPage.html"></iframe>
<div>zzzz</div>
<div>zzzz</div>
<div>zzzz</div>
...much more content...

When you load the parent page – you may get an unexpected result:

scrollIntoView wrong way

The entire page is scrolled! So the item is again present at the top of the page – from inside of iframe. This may not be behavior that you want. If you expected element to scroll into view within the iframe only without affecting the parent page scrolling – a slightly different approach is required:

document.documentElement.scrollTop = document.getElementById("xB").offsetTop;

Here we take element’s offset and assign it to element’s parent scroll – making entire parent scroll to the element position – and the effect is contained within the iframe.

Note: If your parent element is not the document itself – use that parent instead of documentElement in the above example. Note also that some adjustments for parent’s own offset top may be required.

Leave a Reply

Your email address will not be published. Required fields are marked *