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.
forward, then scroll offset is the amount the top of the sliver has been scrolled past the top of the viewport. This value is typically used to compute whether this sliver should still protrude into the viewport via SliverGeometry.
The scrollTop() method sets or returns the vertical scrollbar position for the selected elements.
Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .
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).
Also supported by Internet Explorer.
function position(elem) { var left = 0, top = 0; do { left += elem.offsetLeft-elem.scrollLeft; top += elem.offsetTop-elem.scrollTop; } while ( elem = elem.offsetParent ); return [ left, top ]; } var elem = document.getElementById('id'); position(elem); Subtract the scroll positions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With