Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Retrieve the position (X,Y) of an HTML element relative to the browser window

I need to realize how to get the X and Y position of HTML elements, for example, img and div in JavaScript comparative with the browser window.
by

2 Answers

aashaykumar
The libraries go to some lengths to get accurate offsets for an element.
here's a simple function that does the job in every circumstances that I've tried.

function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('yourElId') ).left;
RoliMishra
You can add two properties to Element.prototype to get the top/left of any element.

Object.defineProperty( Element.prototype, 'documentOffsetTop', {
get: function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
}
} );

Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
get: function () {
return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
}
} );


This is called like this:

var x = document.getElementById( 'myDiv' ).documentOffsetLeft;

Login / Signup to Answer the Question.