Tech Musings

Thursday, December 21, 2006

iFrame Scroll to Anchor Problem

After almost eight hours of trial and error I managed to stitch together a solution for a scrollTo problem I was having with a page that included layers and frames. At issue was the need to maintain an anchored scroll position in an external page that loaded in an iframe (frame), but to make sure the parent page's header (which was contained in a DIV element) would remain visible at the top of the window. It was very similar to the problem described in the following thread that was never fully resolved:

http://www.thescripts.com/forum/thread89747.html

The scrollTo on page load event I first used worked great in Mozilla, Safari and even Internet Explorer on the Mac. However, the problem resided with Internet Explorer on Windows. In IE, the anchored content in the iFrame always took precedent (because it loaded last?) and jumped (scrolled) the main browser window down to the same target point as anchored in the iFrame, which in turn hid the DIV element at the top of the page. I solicited help here in the WebDeveloper forum but didn't receive a response. I continued to attack the problem with javascript using different layer and frame load order combinations without much success.

I finally resolved the issue by calling the scrollTo in an onLoad event in the frame element instead of in the HTML body tag. Ahh HAAA!!

Here is the code:

<script>
function loadorder() {
document.getElementsByName("iframename")[0].src= "http://www.foo.com/bar.htm#anchor_on_page"
window.scrollTo(0,0)
}
</script>

---

<iframe width="830" src="http://www.foo.com/bar.htm#anchor_on_page" height="500" scrolling="yes" frameborder="0" id="iframename" name="iframename" style="top: 200px; left: 0px; position:absolute" onLoad="loadorder();"></iframe>


I gleaned helpful information from the following sources:

http://groups.google.com/group/microsoft.public.scripting.jscript/
http://www.webmasterworld.com/forum21/7779.htm
http://www.dynamicdrive.com/forums/showthread.php?t=10557
http://www.dhtmlcentral.com/tutorials/tutorials.asp?page=3&id=5
http://www.tizag.com/javascriptT/javascript-getelementbyid.php