views:

39

answers:

1

I'm trying to find the location of an element on the screen using javascript. This is what I'm doing.

function locateTargets(){
    var targets = document.getElementsByTagName("span");
    for(var i = 0;i<targets.length;i++){
        if(targets[i].className == "target"){
            targetsY[targets[i].getAttribute("id")] = targets[i].offsetTop;
        }
    }
}

This works fine in Firefox, Chrome and IE, but Opera and Safari end up finding 0 for all but the last element.

Any ideas why this might be happening and how to fix it?

A: 

offsetTop finds the top location relative to the last absolutely-positioned parent/ancestor element (document.body is the first absolutely-positioned ancestor element for any other element).

It looks like Opera has a bit of trouble with document.body and even fixed elements.

If these are not your issues, posting a bit of code may help us help you troubleshoot.

palswim
I think this might be the issue, especially if Safari has similar problems. What throws me off is this:I find seven elements with class="target". Six of them return 0 for their offsetTop, but the last one returns the correct value. So it DOES work somehow. Just not consistently. I double and triple checked the actual span tags and they are all identical (except for their ids of course).
Skunkwaffle