Jump to the top of outer frame, from inner frame

by EvanJPalmer


I have a long-ish form on my site. When you submit this form a validation message appears at the top of the screen and the page is scrolled up – I’m not particularly fond of this UX, but that’s how it is unfortunately.

Now, this works well on the site, but when I embed this in Facebook, inside an iFrame, it no longer scrolls. That’s becuase the inner frame is already set to 100% (so there’s no way to scroll the frame, and we don’t have access to the outer frame, or window.document, because that’s controlled by Facebook.

So how can I make it scroll to the top in this case?

I ended up just usign javascript to focus on a div that I placed at the top of the page. I’m aware this is a hack, but it really helps the UX when using Facebook, so i think it’s warranted.

Here’s code:

function jumpToTopOfIframe() {<
var facebookTop = document.getElementById('facebooktop');
if (facebookTop != null) {
    facebookTop.text = '.';
    facebookTop.text = '';

And the mark up:

<div tabindex="0" id="facebooktop" name="facebooktop"><!-- This is here so we can jump to the top of the frame when loaded in facebook. It needs to be visible (not display: none). --></div>

What’s going on:

I’ve put a div at the top of the page that I want to target and given it an Id so I can access to it, and a tab index so the browser is able to focus on it (a tab index of zero means the browser can work it out). Now, I don’t want the div visible, but I can’t put a dispay: none on it, because the browser won’t let us focus on a div with no display. Likewise it needs some text it in. So in the javascript, I show the frame and add some text, now I can focus on it. I then remove the inner text and hide it so it doesn’t screw with the layout.

And that’s it.

Hacky? Yes. But it works.

…I should get that last line printed onto a t-shirt.