i need some help about finding elements position. im working on an e-book reader, also its all Html with css. All html sectioned page by page, and i have to find an element like this
<span name="Note" style="background-color:rgb(255,255,204)">Example</span>
Everyone suggests code like this;
function position(elem) { var left = 0, top = 0; do { left += elem.offsetLeft; top += elem.offsetTop; } while ( elem = elem.offsetParent ); return [ left, top ]; }position(document.getElementsByName('Note')[0]);
but it does not work for me; I need element’s real position in scroll with JavaScript.
Advertisement
Answer
var note = document.getElementsByName('Note')[0]; var screenPosition = note.getBoundingClientRect();
The ClientRect returned by getBoundingClientRect()
has values for .top
, .left
, .right
, .bottom
, .width
, and .height
.
These are pixel positions on the visible window; as you scroll the page the .top
and .bottom
values will change, and may even become negative as the item scrolls off the top of the view.
Note that—unlike the solution accumulating offsetLeft
/offsetTop
—this solution properly accounts for borders and padding on the body
and html
elements in all browsers (Firefox).
See this test case: http://jsfiddle.net/QxYDe/4/ (scroll the page and watch the values change).