dannytalk ™ A Danny Ng Blog

Danny Ng blogs about SEO, Web Development, Christianity, and Life in General

Javascript Cumulative Offset

Posted by danny On September - 21 - 2008

I just wrote a simple helper function that gets the cumulative offset of the x and y position (or the cumulative top and left) of an element. This function is helpful if you want to position things around a certain element.

Although I haven’t tested it extensively yet, I think it works fine so far. If there’s any bugs, please let me know.

To use it, simply call getCumulativeOffset(element).x or getCumulativeOffset(element).y. There’s also a simple helper method to get the offsetTop and offsetLeft properties by calling getOffset(element).x and getOffset(element).y.

I’m working on a feature that allows these methods to be prototypes of HTML elements so that you can call it by element.getCumulativeOffset().x instead which is more elegant and object oriented.

/**
 *  @author:    Danny Ng (http://www.dannytalk.com)
 *  @date:      21/09/08
 *  @notes:     Free to use and distribute for non-commercial use without altering this notice. Would appreciate a link back.
 */
function getCumulativeOffset(el)
{
	var x = 0;
	var y = 0;
	var cur = (el) ? el : this;
	do
	{
		if (cur.nodeName.toLowerCase != 'td')
		{
			x += cur.offsetLeft;
			y += cur.offsetTop;
		}
	}
	while ((cur = cur.offsetParent) && cur.nodeName.toLowerCase() != 'body');	

	return { x: x, y: y };
}

function getOffset(el) { return (el) ? { x: el.offsetLeft, y: el.offsetTop } : { x: this.offsetLeft, y: this.offsetTop }; }

Bookmark This!

http://www.dannytalk.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/furl_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/newsvine_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/google_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/yahoobuzz_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/sphinn_48.png http://www.dannytalk.com/wp-content/plugins/sociofluid/images/twitter_48.png