tags:

views:

695

answers:

3

Hi,

I have an iframe window that displays a report. To access this iframe, I have an expand/collapse button on the parent window.

Within the iframe report window, I have a #PAGETOP anchor at the bottom of the report, i,e:

<tr><td style="padding-left:45px" class="bottom" colspan="99"><div id="ptAnchor"><a href="#PAGETOP"><img src="first.png" border="1" alt="Top of Page" /></a></div></td></tr>

How can I programatically emulate an onclick of this #PAGETOP anchor, when the user presses the "expand" button from the parent window?

Thanks, Tony.

+1  A: 

The use of #PAGETOP anchor is to scroll the window to the top. You can instead write a function to scroll the window to 0,0 coordinates.

function ScrollToTop() {
    window.scroll(0, 0);
}

Put this function in the IFrame, and call it from the parent window.

Kirtan
Hi Kirtan, unfortunately this didn't seem to work. Would still appreciate how I would do this progrmatically - thanks.
tonsils
Any such fix requires the same domain in the src of the iframe. See http://en.wikipedia.org/wiki/Same_origin_policy
American Yak
A: 

You can do something like this:

<iframe name="foo"></iframe>
<button>Expand</button>

<script type="text/javascript">
  $(function(){
    $('button').click(function(){
      window.frames['foo'].location.hash = "top";
    });
  });
</script>
tom
+1  A: 

In the parent doc:

<a id="scrollToTop">Expand</a>
<script type="text/javascript">

   document.getElementById("scrollToTop").onclick = function(e) { 
      var childWindow =  document.getElementById("theIFrame").contentWindow;

      // this should emulate a click on the ptAnchor DIV's child A HREF.
      childWindow.document.getElementById("ptAnchor").firstChild.click();

      // alternatively, this will simply scroll the child window to the top-left corner
      childWindow.scrollTo(0,0);
   }
</script>
<iframe id="theIFrame" src="someDocOnTheSameDomain.html"></iframe>

Your iframe must be on the same domain for the browser to allow scripting between the parent and child frames.

The contentWindow property allows you to access the window object of the child iframe. From there, you can write Javascript to emulate a click or simply scroll the window around.

Jeff Meatball Yang