Calculating an Element’s Distance From the Top of the Document
For the times that I need to know how far an element is from the top of the DOM, not the top of it’s parent, I use this helper function.
//Loops through all parent nodes of an element to get it's distance from the top of the document function getDistanceFromTop(element) { var yPos = 0; while(element) { yPos += (element.offsetTop); element = element.offsetParent; } return yPos; }
This function returns the number of pixels the top of the element is from the top of the DOM.