Find window coordinates of the field
In the iframe below you can see a document with the green “field”.
There’s a small feature implemented in the document for convenience. A click at any place shows coordinates there.
Your code should use DOM to get window coordinates of:
- Upper-left, outer corner (that’s simple).
- Bottom-right, outer corner (simple too).
- Upper-left, inner corner (a bit harder).
- Bottom-right, inner corner (there are several ways, choose one).
The coordinates that you calculate should be the same as those returned by the mouse click.
P.S. The code should also work if the element has another size or border, not bound to any fixed values.
Outer corners are basically what we get from elem.getBoundingClientRect().
Coordinates of the upper-left corner
answer1 and the bottom-right corner
let coords = elem.getBoundingClientRect(); let answer1 = [coords.left, coords.top]; let answer2 = [coords.right, coords.bottom];
Left-upper inner corner
That differs from the outer corner by the border width. A reliable way to get the distance is
let answer3 = [coords.left + field.clientLeft, coords.top + field.clientTop];
Right-bottom inner corner
In our case we need to substract the border size from the outer coordinates.
We could use CSS way:
let answer4 = [ coords.right - parseInt(getComputedStyle(field).borderRightWidth), coords.bottom - parseInt(getComputedStyle(field).borderBottomWidth) ];
An alternative way would be to add
clientWidth/clientHeight to coordinates of the left-upper corner. That’s probably even better:
let answer4 = [ coords.left + elem.clientLeft + elem.clientWidth, coords.top + elem.clientTop + elem.clientHeight ];