Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element at specified position - JavaScript

People also ask

How do you find the position of an element relative to a window?

We can use the getBoundingClientRect method to get an element's position relative to its viewport. We get the div with querySelector . Then we call getBoundingClientRect on it to get an object with the top and left properties. top has the position relative to the top of the viewport.

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 width of a DOM element?

Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.


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


You can use the native JavaScript elementFromPoint(x, y) method, that returns the element at coordinates x,y in the viewport.

See the elementFromPoint w3c draft

And, a code sample:

function changeColor(newColor) {
    // Get the element placed at coords (2, 2)
    var elem = document.elementFromPoint(2, 2);
    // Set the foreground color to the element
    elem.style.color = newColor;
}
<p id="para1">Change this text color using the following buttons.</p>
<button onclick="changeColor('blue');">Blue</button>
<button onclick="changeColor('red');">Red</button>

You can use setInterval() to continuously check the element's hover event but it's not recommended, try to use .hover(...) and css instead to enhance the application performance.


To get the topmost element at a specific position relative to the viewport, document.elementFromPoint(x, y) can be used.

To obtain an array of all the elements at a specific position, use document.elementsFromPoint(x, y).

In both cases, x is the horizontal coordinate which is relative to the left of the viewport and y is the vertical coordinate which is relative to the top of the viewport.