38

i would like to retrieve the element offset starting from his own x center coordinates.

how can i do it?

Actually i can find the window offset of an element but it retrieves the coordinates from the border of the element like this:

var _position = $(this).offset();
H.B.
  • 166,899
  • 29
  • 327
  • 400
itsme
  • 48,972
  • 96
  • 224
  • 345
  • I'm not sure what you're trying to get, the position of the middle of your element instead of its most left-top? Also, $position isn't a right syntax, if so just add width/2 to the X and height/2 to the height and you're good. – Shai Mishali Nov 06 '11 at 14:59
  • @ShaiMishali That is the right syntax. It works perfectly. It only isn't the convention to name variables like that in JavaScript. – Some Guy Nov 06 '11 at 15:03

2 Answers2

65

You have to use offset() to get the top and left position, then add half of the height() and width() values to them. That gives the center coordinates.

var $this = $(this);
var offset = $this.offset();
var width = $this.width();
var height = $this.height();

var centerX = offset.left + width / 2;
var centerY = offset.top + height / 2;

If you need to consider the padding property in your calculations, use the following:

var width = $this.outerWidth();
var height = $this.outerHeight();
Will
  • 732
  • 9
  • 21
Rob W
  • 341,306
  • 83
  • 791
  • 678
21

This can now be done through native Javascript also:

let centerX = targetNode.offsetLeft + targetNode.offsetWidth / 2;
let centerY = targetNode.offsetTop + targetNode.offsetHeight / 2;

where targetNode is the element you want to get its center coordinates.

Strategist
  • 633
  • 1
  • 9
  • 11
  • 5
    This only figures out the center relative to the targetNode's OffsetParent. Any parent element (all the way up the tree) with positioning other than static (the default) will effect this. – Fusty Jan 08 '19 at 18:03
  • 2
    this method returns undefined in svg objects – Fathy Jan 31 '21 at 21:24