0

I know plenty of ways to calculate the offset or position of an element with jQuery, but I am working on a library that will be used by clients who may or may not be using jQuery and I need to keep it as small as possible.

Is there a lightweight library or an example somewhere that works the same way as the jQuery's offset() function?

tshepang
  • 12,111
  • 21
  • 91
  • 136
taxilian
  • 14,229
  • 4
  • 34
  • 73
  • You can use the [Computed Style](http://stackoverflow.com/questions/6134471/have-problem-when-use-elements-that-added-to-an-array-with-document-getelementb/6134501#6134501) and look for the `top` and `left` property – Ibu Apr 05 '12 at 16:51
  • 1
    Take a look: https://github.com/jquery/jquery/blob/master/src/offset.js – karim79 Apr 05 '12 at 16:52

2 Answers2

3
elem.offsetLeft
elem.offsetTop

These two properties tell you the position of the element elem relative to its offsetParent. The offsetParent of an element is usually a container with position: relative, a table, or the document itself (or a few other things I don't remember).

You can loop through the offsetParent chain until there are no more parents, adding the offsetLeft and offsetTop together to get the position relative to the whole page.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • My understanding is that this method doesn't always work on some versions of Internet Explorer; am I mistaken? – taxilian Apr 06 '12 at 15:32
  • Ahh; I remembered there was an issue. This method does not take into account any borders set on various parent containers – taxilian Apr 07 '12 at 00:40
  • Really? That's odd, never had that problem myself... Still, that can be fixed by getting `computedStyle(elem)['border-width']` (and for older IE: `function computedStyle(elem) {return elem.currentStyle;};`) – Niet the Dark Absol Apr 07 '12 at 00:41
  • .. and walk up the DOM doing that. Yeah, I think I'll end up having to just port the jQuery offset into a standalone library. Somewhat annoying. I'm still shocked that nobody else seems to have done it. – taxilian Apr 07 '12 at 00:42
0

Look at jquery's code and see how it calculates element positions.

Keep in mind that jquery is designed to work everywhere.

Michael Slade
  • 13,802
  • 2
  • 39
  • 44
  • I know that I can steal code from jquery, but that ties into a lot of other parts of jquery and makes it a non-trivial task to take from the file that @karim79 linked to above; I guess I just figured that someone else might have sometime needed to solve the problem in a cross-platform way that couldn't use jquery before me – taxilian Apr 06 '12 at 03:58