Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery x y document coordinates of DOM object

I need to get the X,Y coordinates (relative to the document's top/left) for a DOM element. I can't locate any plugins or jQuery property or method that can give these to me. I can get the top and left of the DOM element, but that can be either relative to its current container/parent or to document.

like image 781
DMCS Avatar asked Jun 16 '09 17:06

DMCS


People also ask

How do you find XY coordinates of a div?

If the element is in the main document you can get the DIV's coordinates with... var X=window. getComputedStyle(abc,null). getPropertyValue('left'); var Y=window.

How do you find the position of an element at the top?

The correct approach is to use element. getBoundingClientRect() : var rect = element. getBoundingClientRect(); console.

How do you find the coordinates of an element?

Use the Element. getBoundingClientRect() Function to Get the Position of an Element in JavaScript. The getBoundingClientRect() function produces a DOMRect object containing information about an element's size and position in the viewport.

What is offset () in jQuery?

jQuery offset() Method The offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.


1 Answers

you can use Dimensions plugin [Deprecated... included in jQuery 1.3.2+]

offset()
Get the current offset of the first matched element, in pixels, relative to the document.

position()
Gets the top and left position of an element relative to its offset parent.

knowing this, then it's easy... (using my little svg project as an example page)

var x = $("#wrapper2").offset().left; var y = $("#wrapper2").offset().top;  console.log('x: ' + x + ' y: ' + y); 

output:

x: 53 y: 177 

hope it helps what you're looking for.

here's an image of offset() and position()

using XRay

alt text

using Web Developer toolbar

alt text

like image 55
balexandre Avatar answered Oct 13 '22 13:10

balexandre