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

Add Your Own


bluehost.com ad


Recent Posts

  • Automating the next-episode button in Netflix
  • Lessons learned from Apple's Design Process
  • On why I started another Redesign when I had just finished one.
  • Why I chose Bluehost for cheap, reliable hosting (review)
  • Break; and continue; in javascript loops
  • -->