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.
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.
The correct approach is to use element. getBoundingClientRect() : var rect = element. getBoundingClientRect(); console.
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.
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.
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
using Web Developer toolbar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With