PDA

View Full Version : one more offsetTop question



Peter Johnson
03-07-2007, 06:23 PM
I've been trying to figure out how to get an element's offsetTop position, when the element is within a table. The script below works fine outside of a table, but returns -1 when it's in a table, or if there are tables anywhere on the page.

I know (think?) I need to keep climbing the "tree" to get to the top of the page, and have seen scripts such as at http://www.quirksmode.org/js/findpos.html, but can't figure out how to apply them. Could someone show me how this script could be re-written to get the "sectionaposition" when there are tables? I need to use offsetTop, and I need to use it on a site that has tables, so eliminating the tables or using something other than offsetTop aren't options at this point. Thanks.



<html>
<head>
</head>
<body>
<p>lorum ipsum</p>

<table><tr><td>


<div id="sectiona">
Section A
</div>

<div id="sectionb">
<script type="text/javascript">
var sectionaposition = document.getElementById('sectiona').offsetTop;
document.write(sectionaposition);
</script>
</div>

</td></tr></table>

</body>
</html>

Peter Johnson
03-08-2007, 01:37 AM
Here's another version I've tried. This one works in Firefox, Opera, but not IE7



<html>
<head>
</head>
<body>
<p>lorum ipsum</p>

<table><tr><td>

<div id="sectiona">
Section A
</div>


<div id="sectionb">

<script type="text/javascript">
var sectionaposition = document.getElementById('sectiona');
function getRealTop(el) {
yPos = el.offsetTop;
tempEl = el.offsetParent;
while (tempEl != null) {
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return yPos;
}
trueY = getRealTop(sectionaposition);
document.write(trueY);
</script>

</div>

</td></tr></table>

</body>
</html>

Veronica
03-08-2007, 02:43 PM
IE7 is buggy about tables. You need to add <tbody> and </tbody> tage.
Also, the javascript will not work so long as it is in the table. It needs to be moved to the end of the page, just before you close the body tag.

Saz
03-26-2009, 03:25 PM
Hi Peter,

Have had a similar problem - did you find an answer please ?

Saz