views:

2083

answers:

3

Does anyone know how to retrieve an iframe top position within a page for IE6 using JavaScript?

The following code works for IE7: window.frames(0).screenTop

but the same code in IE6 retrieves the wrong value (far too high).

Any ideas?

A: 

This looks like a dupe of this question: Dyanamically reterive Html element (X,Y) position with JavaScript

Gary Green
A: 

You might wish to use offsetTop. Of course, you'll have to loop, adding the offsetParent's offsetTop until the offsetParent is null.

Both jQuery and Prototype do this for you.

In fact, here's the code from Prototype:

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if (element.tagName.toUpperCase() == 'BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p !== 'static') break;
      }
    } while (element);
    return Element._returnOffset(valueL, valueT);
  }
  //Element.getStyle returns the style or its default if not defined.
  //Element._returnOffset returns the left and top as a single object
geowa4
+1  A: 

Does anyone know how to retrieve an iframe top position within a page for IE6 using JavaScript?

The same way as for any other element, using offsetTop (and adding up offsetTop from any offsetParent ancestors). It doesn't matter that it's an <iframe> element.

var el= document.getElementsByTagName('iframe')[0];
var top= 0;
while (el && el.nodeType==1 && el!==document.documentElement) {
    top+= el.offsetTop;
    el= el.offsetParent;
}

The following code works for IE7: window.frames(0).screenTop

I doubt that works. screenTop is the wrong thing, it's the on-screen co-ordinates not on-page. And in any case it would have to be square brackets.

bobince