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 (https://www.dannyism.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 }; }
What IE bugs are there regarding relative offsets? I’ll try to look into it. I only test my scripts in IE7 and Firefox. Don’t have time for other browsers unfortunately.
It looks pretty good, though a little more complicated than equivalent code that I’ve seen so far. Also it still doesn’t address the IE bug regarding relative offsets.