Back to the lesson

Find window coordinates of the field

importance: 5

In the iframe below you can see a document with the green “field”.

Use JavaScript to find window coordinates of corners pointed by with arrows.

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:

  1. Left-upper outer corner (that’s simple).
  2. Right-bottom outer corner (simple too).
  3. Left-upper inner corner (a bit harder).
  4. Right-bottom 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.

Open a sandbox for the task.

Outer corners

Outer corners are basically what we get from elem.getBoundingClientRect().

Coordinates of the upper-left corner answer1 and the bottom-right corner answer2:

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 clientLeft/clientTop:

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
];

Open the solution in a sandbox.