9

Hello there

I have an element with fixed position, I can't detect position and must be use javascript clearly, without frameworks (jquery, mootools, etc).

vusan
  • 5,221
  • 4
  • 46
  • 81
mrsum
  • 208
  • 2
  • 6
  • 1
    Possible Duplicate : http://stackoverflow.com/questions/442404/dynamically-retrieve-the-position-x-y-of-an-html-element – Pranav 웃 Jan 11 '13 at 06:45

4 Answers4

11

Use:

var boundingBox = node.getBoundingClientRect();

Check out the result, you have an object like this:

top    : 0,
right  : 0,
bottom : 0,
left   : 0,
width  : 0,
height : 0
Totty.js
  • 15,563
  • 31
  • 103
  • 175
5

Does this help:

document.getElementById('id').offsetLeft // + window.scrollX
document.getElementById('id').offsetTop // + window.scrollY

You might want to look at : This Question

Community
  • 1
  • 1
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
  • If you want to get the same result as what jQuery gives, you need to minus margin. –  Apr 06 '18 at 00:15
2
function findPos(obj) {

    var curleft = curtop = 0;

    if (obj.offsetParent)
    do {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;

    } while (obj = obj.offsetParent);

    return [curleft,curtop];
}

http://www.quirksmode.org/js/findpos.html

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
  • You have a syntax problem first of all, you open the "{" (look at "if (obj.offsetParent) {" ) but you don't close it! Anyway this doesn't work for scrolled divs. – Totty.js Sep 23 '14 at 13:30
0

For a cross platform solution, you might want to look at the the micro-framework Popper.js source. I found your question by trying to resolve this popper problem, but I believe it is applicable to any fixed element.

Capripot
  • 1,354
  • 16
  • 26