eselk eselk - 1 year ago 42
HTML Question

Anchor links inside iframe does nothing

Is it possible to have a non-scrolling iFrame inside a scrolling div, and have anchor links inside the iFrame work correctly? The anchor links inside the iFrame should scroll to the spot inside the iFrame, I don't need/want them to point to elements on the parent page.

Here is my jsFiddle with a simple example:

and the code for it:

<div style="width: 100%; height: 300px; overflow: auto;">
<iframe style="width: 100%; height: 2000px;" src="" scrolling="no"></iframe>

I have no association with that link used in my example, it was just the first example I could find of a page with an anchor by id/name syntax link in it.

If you load the JSFiddle and click the "Jump to Bottom" link inside the iFrame, it does nothing (testing with FireFox 19.0.2). When testing with various pages it never works in FireFox, in Chrome it sometimes works the first time it is clicked, but then if you scroll up and click again it doesn't work. In IE8 it works (scrolls) most of the time.

Scrolling works correctly all of the time if I let the iFrame itself have the scrollbars (remove scrolling="no"). This isn't a practical solution for me though, as I have content outside of the frame that I want to scroll with it. In my real code I dynamically set the height of the iFrame to fill its content, this way it appears to be more like content on my page.

Additional info as to why I need to do this:

I'm creating a web-based email client and so far there seems to be the least amount of issues if I display the HTML body of emails inside an iframe, vs trying to display inside a table cell or div inside my page. I'd like for these type of links to work. I do have some control over the content, it comes from my server and I can modify it some (but don't want to hack it too much). For example, I already modify all links to open in a new window (but not links that start with #, so that isn't my issue).

I know GMail doesn't use iFrames, but my XFINITY (by Comcast cable) web-based email client does, and they managed to get these to work (but so far haven't figured out what all they are doing).

Sam Sam

Check out this post: Jump Link Inside an iFrame

If your iframe has a different domain then you will be unable to use a javascript solution to solve this, but if it is then you can add the target="_parent" attribute to all the anchors within the iframe.

var iframe = document.getElementById('iframeId');
var doc = (iframe.contentDocument)? iframe.contentDocument: iframe.contentWindow.document;

var anchors = doc.getElementsByTagName('a');
for (var i = 0; i < anchors.length; i++)
    anchors[i].target = '_parent';