jQuery get coordinates of element

Sam Deering
Share

jQuery function to get coordinates of element.

The jQuery methods

.position() method allows us to retrieve the current position of an element relative to the offset parent

var pos = $('#wrapper').position();
console.dir(pos);
//output: left: 0, top: 20

.offset(), which retrieves the current position relative to the document.

var offset = $('#wrapper').offset();
console.dir(offset);
//output: left: 70, top: 40

Into coordinates:

var elem = $("#wrapper");
var x = $("#wrapper").offset().left;
var y = $("#wrapper").offset().top;
console.log('x: ' + x + ' y: ' + y);
//output: x: 70 y: 40

jQuery getCoord() function

jQuery.fn.getCoord = function()
{
  var elem = $(this);
  var x = elem.offset().left;
  var y = elem.offset().top;
  console.log('x: ' + x + ' y: ' + y);
  //output: x: 70 y: 40

  return {
      "x" : x,
      "y" : y
  };

  //note that it is not efficient as it breaks the jQuery chain
  //return elem;
};

$('#wrapper').getCoord();
//output: Object { x=70, y=40 }