Find the position of an element with JavaScript

Quirksmode provides a nice findPos() function to find the absolute position of an element on a page.

If you need to find the position of the element relative to the viewport then you will also need to know the page’s current scroll position, which I found over at Stack Overflow.


Bringing these couple together we get:

var util = {
 
	// findPos() by quirksmode.org
	// Finds the absolute position of an element on a page
	findPos: function(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {	
			do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;	
			} while (obj = obj.offsetParent);
		}
		return [curleft,curtop];
	},
 
	// getPageScroll() by quirksmode.org
	// Finds the scroll position of a page
	getPageScroll: function() {
		var xScroll, yScroll;
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;
		}
		return [xScroll,yScroll]
	},
 
	// Finds the position of an element relative to the viewport.
	findPosRelativeToViewport: function(obj) {
		var objPos = this.findPos(obj)
		var scroll = this.getPageScroll()
		return [ objPos[0]-scroll[0], objPos[1]-scroll[1] ]
	}
 
}

I needed to position a jQuery UI Dialog relative to another element on a page and found these functions worked well to get my dialog nicely positioned in IE6, IE7, IE8, Safari, Firefox and Chrome.

This entry was posted in JavaScript and tagged , , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

3 Comments

  1. Raj
    Posted May 24, 2010 at 1:24 pm | Permalink

    how different the .position() and .offset() methods of jQuery from this?. may be I am missing something.

  2. Posted May 24, 2010 at 8:26 pm | Permalink

    Hi Raj

    Thanks for letting me know about those functions.

    It looks like .offset() returns the equivalent of the findPos() function above.

    The .position() function, according to the jQuery docs, returns the coordinates relative to the offset parent.

    I did a quick search but didn’t find any jQuery function that helped me to find the position relative to the viewport, so I might still need to use the getPageScroll() function.

    Thanks

  3. Adam B
    Posted January 5, 2011 at 7:05 am | Permalink

    Thanks Kevan. I found the position and scroll solutions independently, but your post was a nice integration of the two concepts…especially for folks in a position where jquery isn’t an option.