Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get real positions of element in javascript

Tags:

javascript

dom

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..

like image 717
Mahmut Duman Avatar asked Apr 04 '13 16:04

Mahmut Duman


1 Answers

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.

like image 119
Sayan J. Das Avatar answered Oct 04 '22 22:10

Sayan J. Das