How to retrieve iframe top position in IE6 using JavaScript?

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?

Answers


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.


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

Need Your Help

JSTree - disable selection on a parent node, but allow expansion on click

javascript jquery jstree

I'm trying out the excellent JSTree 3.0.2. I have a tree with one level of child nodes. When a parent node is clicked I want it to expand, but I don't want the parent node to be selectable - only...

Symfony2 embedded form - get entity field

php symfony2 twig entity-relationship

I have an entity with a many-to-many association.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.