To detect the position of a DOM element (for example, HTMLdiv tag or p
tag) in JavaScript is an interesting topic. In [1], [2], [3], and [4],
there are discussion and code for detecting the position of a DOM elemenet. In
[5], [6], [7], there are discussion and code for detecting the scroll
position of a DOM element. In this post, sample code for detecting the DOM
element position, including scroll position, will be shown.
<!doctype html><html><head><metacharset="utf-8"><title>JavaScript DOM Element Position (Scroll Position Included) Example</title></head><body><div>There are 4 buttons in this page, try to click them to get position.</div><brstyle="line-height: 2em;"/><buttononclick="javascript:onButtonClick(this)">click me to get my position(1)</button><br/><brstyle="line-height: 20em;"/><divstyle="text-align: center;"><buttononclick="javascript:onButtonClick(this)">click me to get my position(2)</button></div><brstyle="line-height: 20em;"/><buttononclick="javascript:onButtonClick(this)">click me to get my position(3)</button><br/><brstyle="line-height: 20em;"/><divstyle="text-align: center;"><buttononclick="javascript:onButtonClick(this)">click me to get my position(4)</button></div><scriptsrc="position.js"></script></body></html>
The sample code above, however, is not complete. The code will not work if
CSS margin property and absolute display property of a DOM element is set.
For example, if the website designer uses the semi-fluid layout mentioned in
this holy grail tutorial, the code above will not work because the margin and
relative position is not taken into consideration in the sample code. The
position function provided by jQuery in [11] will still work under such
circumstance. I tried to trace the source code of jQuery in [10], but still
cannot figure out how to do it. Maybe I will be back to this issue some time.