Find x and y position of an element using JavaScript
1 of November2007
Ever needed to find the x or y coordinates of an element on a page? Well, thanks to this script from quirksmode it’s possible.
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
var elemToFind = document.getElementById('div1');
var elemCoords = findPos(elemToFind);
So now, elemCoords holds both the x and the y. Since findPos() returns an array, to access the x or y by itself do the following:
// elemCoords[0] or elemCoords[1] for the x and y values, respectively alert(elemCoords[0]);
Tags: Coding, JavaScript
Posted in JavaScript |
RSS 2.0 Feed for comments