15

enter image description here

I want to get real X and Y position of my styled elements in javascript ( or jquery short code).

var offset = obj.offset();
  ox=offset['left']; 
  oy=offset['top']; 

  px=parseInt(obj.css('padding-left')); // padding left
  py=parseInt(obj.css('padding-top')); // padding top
  bx=parseInt(obj.css('border-width') ); // stroke value
  ox=ox+px+bx;
  oy=oy+py+bx;

But this codes sometimes not work..

when scrool top or scroll left change im not get real position :(

please help me..

2
  • 1
    Are you getting unreal position now ?
    – adeneo
    Apr 4, 2013 at 16:20
  • 1
    (OT) try always to use dot notation: offset.left , and don't forget that parseInt likes his radix parameter. Apr 4, 2013 at 16:23

4 Answers 4

17

You don't have to use offsets. Use the modern getBoundingClientRect function:

function getPosition( element ) {
    var rect = element.getBoundingClientRect();
    return {
        x: rect.left,
        y: rect.top
    };
}

You could then use the above function like this:

var element = document.getElementById( 'myElement' );
var pos = getPosition( el );

// Alert position in X axis
alert( pos.x );

// Alert position in Y axis
alert( pos.y );

Works in all browsers 🙂

EDIT: If you want the position of the element with respect to page scroll, just add document.body.scrollTop to Y position and document.body.scrollLeft to X position.

1
0

You'll want the offset from the element relative to the document. You have to keep in mind that styles like padding, margin and border can greatly affect the result of the offset. You might want to calculate those on or off the offset.

Finally you need to check if you are using box-sizing, which pushing padding and borders to the inside (with the most common version box-sizing: border-box;);

document.getElementById('cloud').offsetLeft; //offsetTop

Just debug with the other styles (adding/subtracting) until you get the real offset. I mostly test if the offset is correct by making a screenshot (or using the OS X selective-screenshot function) to see if the offset is correctly calculated (counting pixels) with the other styles.

Here's a little example:

CSS

#cloud {
    height: 500px;
    width: 500px;
    margin: 20px auto;
    border: 1px dotted #CCC;
}

HTML

<body>
    <div id="cloud">
        <div id="centerBox"></div>
    </div>
</body>

JavaScript

'use strict';

console.log(document.getElementById('cloud').offsetLeft);
console.log(document.getElementById('cloud').offsetTop);

Ouput

main.js: 1 >>> 372
main.js: 2 >>> 20

Funny thing here, you can easily test if the offsetLeft works because of the margin: 20px auto;. If you resize the window it will also have a different offsetLeft.

4
  • var offset = obj.offset(); ox=offset['left']; = document.getElementById('Mypicture').offsetLeft; Two codes are get equal value.. but not get padding,border values :( Apr 4, 2013 at 18:59
  • Did you read everything in my answer? I already explained that you have to take into account those factors. And by the way; they do the get the "real" values, but not the ones that you want. I already noted in my answer that you have to see which spatial factors change the basic offset, like padding and borders. Also don't use negative margins/paddings unless it's really necessary. It's bad practice. And remember that if you do padding: 20px; the height of the element will become 40px (2x20px) higher.
    – user1467267
    Apr 4, 2013 at 19:11
  • 2
    and by box-content you mean box-sizing right? quirksmode.org/css/user-interface/boxsizing.html
    – John Lewin
    Oct 3, 2013 at 17:12
  • offset won't account for margin. getBoundingClientRect().left (for example) will, and you don't have to traverse the DOM.
    – Modular
    Jan 11, 2017 at 5:59
0

This function gives you the exact position of an element without padding or margin or border:

function getElementRec(element) {
    let rec = { x: 0, y: 0, width: 0, height: 0 }; 
    
    let computedStyle = getComputedStyle(element);
    rec.width = element.clientWidth;
    rec.width -= parseFloat(computedStyle.paddingLeft);
    rec.width -= parseFloat(computedStyle.paddingRight);
    rec.height = element.clientHeight;
    rec.height -= parseFloat(computedStyle.paddingTop);
    rec.height -= parseFloat(computedStyle.paddingBottom);
    
    let boundingRect = element.getBoundingClientRect();
    rec.x = boundingRect.left;
    rec.x += parseFloat(computedStyle.paddingLeft);
    rec.x += parseFloat(computedStyle.borderLeft);
    rec.y = boundingRect.top;
    rec.y += parseFloat(computedStyle.paddingTop);
    rec.y += parseFloat(computedStyle.borderTop);
    
    return rec; 
}
-1
     var offset = obj.offset();
      ox=offset['left']; = document.getElementById('Mypicture').offsetLeft;
      oy=offset['top'];  = document.getElementById('Mypicture').offsetTop;
    px=parseInt(obj.css('padding-left')); // padding left
    py=parseInt(obj.css('padding-top')); // padding top
    bx=parseInt(obj.css('border-width') ); // stroke value
    ox=ox+px+bx;
    oy=oy+py+bx;

//Two codes get equal value;  But Not Real clientX ClientY positions..

// My html:

    <div id="container">
    <img id="Mypicture" src="myimage.jpg"  alt="The source image for paint"/>
    </div>

//My css :

  #Mypicture{
  margin:100px;
  padding:20px;
  border: 20px solid #cacaca;
  }

  #container {
  display:block;
  background:#ffaaff;
  width: 550px;
  padding:50px;
  margin-left:300px;
   }

// I want to get realx and realY value of Mypicture,on Document. // All codes work Realx ( ox ) return true value But RealY (oy) nearly 10px false;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.