Retrieve the Position (X,Y) of an HTML Element

Retrieve the position (X,Y) of an HTML element in Ruby

Set some id to element

<html>
<head></head>
<body>
<div id="my-id">
<%= @article.text %>
</div>
</body>
</html>

And get position in JS with getBoundingClientRect

const getCoordinates = (element) => {
const box = element.getBoundingClientRect()

return {
top: box.top + window.pageYOffset,
right: box.right + window.pageXOffset,
bottom: box.bottom + window.pageYOffset,
left: box.left + window.pageXOffset
}
}

const element = document.getElementById('my-id')

const coordinates = getCoordinates(element)

console.log(coordinates)

Reference:

https://javascript.info/coordinates

How to grab the x, y position of html elements with javascript

Use getBoundingClientRect:
http://ejohn.org/blog/getboundingclientrect-is-awesome/

For example:

var div = document.getElementById("yourDiv");
var rect = div.getBoundingClientRect();
alert("Coordinates: " + rect.left + "px, " + rect.top + "px");

Remember that getBoundingClientRect gives the coordinates relative to the current viewport, which means that if you want to know the coordinates relative to the document.body, you have to add the horizontal and vertical scroll amounts (document.documentElement.scrollLeft or document.body.scrollLeft for Firefox, and .scrollTop of course).

getting the X and Y coordinates for a div element

Here a simple way to get various information regarding the position of a html element:

        var my_div = document.getElementById('my_div_id');
var box = { left: 0, top: 0 };
try {
box = my_div.getBoundingClientRect();
}
catch(e)
{}

var doc = document,
docElem = doc.documentElement,
body = document.body,
win = window,
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;

Get element at specified position - JavaScript

document.elementFromPoint(x, y)
document.elementsFromPoint(x, y)

https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint

https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint
https://developer.mozilla.org/en-US/docs/Web/API/Document/elementsFromPoint

Finding element's position relative to the document

You can traverse the offsetParent up to the top level of the DOM.

function getOffsetLeft( elem )
{
var offsetLeft = 0;
do {
if ( !isNaN( elem.offsetLeft ) )
{
offsetLeft += elem.offsetLeft;
}
} while( elem = elem.offsetParent );
return offsetLeft;
}


Related Topics



Leave a reply



Submit