[Javascript] DOCTYPE making div.style.top NOT WORK

Nick Fitzsimons nick at nickfitz.co.uk
Fri Dec 22 11:01:57 CST 2006


On 22 Dec 2006, at 14:20:00, Michael Borchers wrote:

>
> right here guys, we have another "bug" that took me hours to find out.
> here is the script:
> http://www.droeppez.de/download/js-tut/js-tut/tutorial/position.html
>
> works fine, in IE und FF!
>
> it failed when adding it to a huge intranet. hours later I alerted  
> the tagnames of
> eacht tag. after the HTML it cancelled, so what happened?!
> what element could be paren to <html>?!
> now i know:
> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
>
>
> serious guys, it made the script collapse because it thinks <! 
> DOCTYPE is a tag that is parent to <html>
>
> i can't believe it! what now? forget about the DOCTYPE for the  
> future?! ;)
>

IE does do stupid things like thinking that the DOCTYPE is an element  
whose name begins with an exclamation mark, but I think the reason  
you are having problems is that the script you are using is simply  
not very good. It checks for various properties unrelated to  
establishing position of an element, and its approach to moving up  
the DOM tree is flawed. (I shouldn't be too hard on the author, as it  
looks like at least part of what it does the wrong way is based on an  
example on Microsoft's own site...)

Try this:

     function getPosition(element) {
        var position = {x: 0, y: 0};
        while (element) {
           position.x += element.offsetLeft;
           position.y += element.offsetTop;
           element = element.offsetParent;
        }
        return position;
     }

which will (as with your existing script) return an object with "x"  
and "y" properties, and works (in my quick tests) on IE, Firefox,  
Opera and Safari, even with a DOCTYPE declaration.

HTH,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/






More information about the Javascript mailing list