Use jQuery to Scroll to Anchor in an iFrame

I had a unique customer request to provide navigation for content within an iframe on the parent page of the iframe. This is problematic because cross domain scripting would not allow me to handle and manipulate the content in the iframe.

jQuery to the Rescue.

I am confident that this can be done in native javascript, but since my site was already using the jQuery framework, I wanted to go that route. (Work smarter, not harder).

After a bit of trial and error on how to grab the anchor tag, I changed my approach. The solution resided in simply swapping the source of the iframe to include the #achorname at the end of the URL. This would effectively “scroll” the iframe to the proper location. A bit of Googling and I located this snippet of code on jsFiddle to facilitate the URL onclick switching.

The HTML

<ul>
    <li>
        <a href="http://www.123.com/test#anchor1" onclick="return loadIframe('ifrm', this.href);">Nav 1</a>
    </li>
    <li>
        <a href="http://www.123.com/test#anchor2" onclick="return loadIframe('ifrm', this.href);">Nav 2</a>
    </li>
</ul>
<div class="iframe">
    <iframe name="ifrm" id="ifrm" src="http://www.123.com/test" frameborder="0">
        Your browser doesn't support iframes.
    </iframe>
</div>

The JavaScript

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ( $iframe.length ) {
        $iframe.attr('src',url);   
        return false;
    }
    return true;
}

What we are doing is taking the href attribute of the navigation link and replacing the src attribute of the iframe. This will essentially move the iframe content to have the position the anchor at the top of the iframe window. So we don’t truly “scroll” the iframe, but we can navigate the iframe with links on the parent page.

Note: This does require knowledge of the anchor tags. It is easy to view the source to grab that info, but the originating site can change that page at any time.