Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the distance from the top for an element?

Tags:

javascript

I want to know how to use JavaScript to get the distance of an element from the top of the page not the parent element.
enter image description here

http://jsfiddle.net/yZGSt/1/

like image 723
Sami Al-Subhi Avatar asked Aug 04 '12 04:08

Sami Al-Subhi


People also ask

How do you find the distance from the bottom of an element?

You can calculate the space between your element and bottom of the page by calculating element. offsetTop and window. innerHeight . if you want to calculate space between bottom of your element and bottom of the window then you need to add your element height too.

How do you find the height of an element?

In JavaScript, you can use the clientHeight property, which returns an element's height, including its vertical padding. Basically, it returns the actual space used by the displayed content. For example, the following code returns 120, which is equal to the original height plus the vertical padding.

What is offset in JS?

The offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.


2 Answers

var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top 

In my experience document.body.scrollTop doesn't always return the current scroll position (for example if the scrolling actually happens on a different element).

like image 57
eeglbalazs Avatar answered Oct 02 '22 20:10

eeglbalazs


offsetTop only looks at the element's parent. Just loop through parent nodes until you run out of parents and add up their offsets.

function getPosition(element) {     var xPosition = 0;     var yPosition = 0;      while(element) {         xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);         yPosition += (element.offsetTop - element.scrollTop + element.clientTop);         element = element.offsetParent;     }      return { x: xPosition, y: yPosition }; } 

UPDATE: This answer has some problems, values will have tiny differences compare to what it should be and will not work correctly in some cases.

Check @eeglbalazs's answer, which is accurate.

like image 26
Shawn Whinnery Avatar answered Oct 02 '22 21:10

Shawn Whinnery