sbaaaang sbaaaang - 1 month ago 8
jQuery Question

How to find the element's x center coordinates and related window offset

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();

Answer

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;