[Javascript] X and Y co-ordinates of an object

Nick Fitzsimons nick at nickfitz.co.uk
Mon Feb 26 10:41:48 CST 2007


On 26 Feb 2007, at 15:58:38, Alan Easton wrote:

> Hi All,
>
> I am wanting to know the X and Y co-ordinates of an object on a  
> page. It needs to be Firefox, Netscape and IE compatible.
>

Welcome to a world of pain :-(

You might want to start at ppk's site:
<http://www.quirksmode.org/js/elementdimensions.html>
where a look at the compatibility table and associated notes should  
serve to convince you that this is not as easy as you might expect.

In particular, things get complex very quickly if the page has been  
scrolled, if relative or absolute positioning are used, if elements  
within the page are scrolled independently using the CSS "overflow:  
auto;" or "overflow: scroll;" properties, and if iframes get  
involved. And then there are various off-by-a-few-pixel bugs in  
different browsers.

Then have a look at lines 187 to 253 of the dom.js file in the Yahoo!  
User Interface Library:
<http://developer.yahoo.com/yui/>
which is pretty much bulletproof, but may have dependencies on other  
parts of the library. It should at least serve to give you an idea of  
the approach to follow, if you want to write it yourself.

(Note that other JS libraries include similar functionality, so you  
might want to look at their source, as well.)

HTH,

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






More information about the Javascript mailing list