The Javascript libraries have pretty complicated functions to calculate an element's offset on the page. I wrote the following function that works in all the places I need it, and I've tested a few edge cases as well. It adds the element's offsetTop
to its parent's offsetTop
all the way up the DOM to the document
. Can someone give me an example of where this wouldn't work?
This demo shows its results compared to jQuery's offset().top
function.
Demo: http://jsfiddle.net/ThinkingStiff/5aGqM/
window.Object.defineProperty( Element.prototype, 'documentOffsetTop', {
get: function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
}
} );
UPDATE:
I was looking for places where traversing up the DOM and adding the offset doesn't work in current browsers. As @Akkuma pointed out, Object.defineProperty
doesn't work in earlier IEs.