Using Javascript how can I identify the element at a given position? Basically I’m looking to write a function that takes two input parameters (the x and y coordinates) and returns the html element at the position on the screen represented by the parameters.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
Method 2
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.
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0