About

Thoughts on Design is a blog on web design and front-end coding. Served up monthly-ish by Jamis Charles.

Search

You are currently browsing the archives for the JavaScript category.

Categories

Archive for the ‘JavaScript’ Category

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]);