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.
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.
Related
I have a question that is math and also JavaScript related. I'm trying to come up with a function to get me the true coordinate within an element that was clicked. The difficulty here is that the element could be rotated.
Otherwise, we could easily get the coordinate within the element on a click by doing using jQuery:
const ELEMENT_X = event.pageX - object.offset().left;
const ELEMENT_Y = event.pageY - object.offset().top;
Not too sure if these JavaScript objects can help calculate the true coordinate of the element:
DOMPoint
DOMMatrix
We know the coordinate of the click on the viewport, the width and height of the element, its offset left/top and we know the rotation angle (could be negative or positive [-180, 180]). So the function I'm trying to get to return the true coordinate of of any four-sided shape would look something like this:
function getClickedCoordinateOfElement(event, elementDOM, rotationAngleInDegrees) {
let coordinate[];
let x, y;
...
return(coordinate[x, y]);
}
I think the solution requires some manipulation of the Sin or Cos of a triangle, but I'm not too sure.
I forgot to mention that the element is not anchored to the origin and could be anywhere.
How would we get the coordinate of the green dot in relative to the inside of the element? The top left corner (ax) of the element would be (0, 0).
I want to write a JavaScript function that moves CSS3 transformed (scaled, skewed, rotated) div elements to an absolute position in the container box. We are developing a canvas like application. I am using getBoundingClientRect() to find an absolute position and bounding-rect of the element. However, when I move this element to specified position it does not work because x and y position has translated.
Move to (0, 0):
// pseudocode I tried!
const matrix = getTransformationMatrix(elm); // get elements transormation matrix.
const pos = matrix.applyToPoint(0, 0); // find related coordiate of zeroth postion by applying element's matrix
tranlatePosition(elm, pos.x, pos.y);
I expected this to be 100% a no-brainer, but as it turns out, I cannot figure out what the x and y attributes of an svg created and manipulated with Raphael.js mean. I assumed they were the coordinates of the top-left corner of the object in relation to the canvas, but now I'm not so sure.
After creating a canvas (var paper = new Raphael(container,width,height)) and adding an image or rectangle to it, for example, if I retrieve the "x" and "y" attributes using the attr method (e.g. object.attr("x")), they're both at 0. However, if I rotate that object and then retrieve the values of x and y again, the values don't reflect the position of the top-left corner of my object in relation to the canvas anymore.
Can someone please explain this to me?
I fear #afaf12's answer complacently goes only half the distance. He's absolutely correct that transformation logic occurs after the fundamental attributes of a given element and doesn't effect them, but it is certainly possible to retrieve the x and y of that element after transformations are applied. You'll want to use the getBBox method, like this:
var bbox = elem.getBBox();
console.log("Transformed coordinates of element are %s,%s", bbox.x, bbox.y );
Please note that there is some trickiness involved -- this returns the bounding box of the element, which is often a superset of the space occupied by the element -- so there's no guarantee that the returned point will be IN the element.
Another alternative occurs if you're using paths -- path.getPointAtLength also works with transformed coordinates, so you can get the x,y offset of the beginning of a path by calling
var coord = elem.getPointAtLength(0);
console.log("Transformed coordinates of path are %s,%s", coord.x, coord.y );
Rotation is a transformation and it does not change x and y of the object.
http://raphaeljs.com/reference.html#Element.transform
I get mouse coordinates on some web page and save them.
$("div#container").mousemove( function(e) {
client_x = e.pageX;
client_y = e.pageY;
// save x,y
});
Now other person load that same page and i want to show them the same coordinates (x,x position).
How can I get the same point if I have to take in consideration that the div#container is not at same position as it was in my browser (considering screen resolution and scroll)?
I would use $.offset().top and $.offset().left of the parent div container, and calculate the difference from that to the current X and Y coordinates of the mouse cursor.
.offset() always refers to the document and not to the parent of the element.
For example:
$('#element').mousemove(function(e){
var client_x = e.pageX;
var client_y = e.pageY;
var elementOffset = $(this).offset();
client_x -= elementOffset.left;
client_y -= elementOffset.top;
// save x, y.
});
Then, on the other users display, show the coordinates after adding them to his offsets.
This doesn't seem possible because of the variables you mentioned in the question. Screen resolution is the main reason, but, also, it depends on how big their window is. At first, you might think that you could compute the mouse's position relative to fixed points, like divs shown (take Stack Overflow, for example, where the main container of the site doesn't resize with the browser window). But if their window is smaller than the container, you would be making some false assumptions about what they see.
That being said, you can always just compute the mouse position relative to fixed elements you know will be on the screenusing $.offset() and just assume they have their screen showing everything (or check $(window) size) and are using "normal" viewing conditions.
You can use the values returned by offset(), in your example:
$("div#container").offset().left
and
$("div#container").offset().top
to substract them to e.pageXand e.pageY.
offset() function gives you the matched element's position relative to the document (see the docs), so there's no problem if the users scroll down.
Example: http://jsfiddle.net/3jMRS/
Is there a way to select the top most DOM element at a certain x-y position with Javascript?
So give x and y, what DOM element is there?
You can use document.getElementFromPoint.