5 Nisan 2019

Coordinates

To move elements around we should be familiar with coordinates.

Most JavaScript methods deal with one of two coordinate systems:

  1. Relative to the window(or another viewport) top/left.
  2. Relative to the document top/left.

It’s important to understand the difference and which type is where.

Window coordinates: getBoundingClientRect

Window coordinates start at the upper-left corner of the window.

The method elem.getBoundingClientRect() returns window coordinates for elem as an object with properties:

  • top – Y-coordinate for the top element edge,
  • left – X-coordinate for the left element edge,
  • right – X-coordinate for the right element edge,
  • bottom – Y-coordinate for the bottom element edge.

Like this:

Window coordinates do not take the scrolled out part of the document into account, they are calculated from the window’s upper-left corner.

In other words, when we scroll the page, the element goes up or down, its window coordinates change. That’s very important.

Click the button to see its window coordinates:

If you scroll the page, the button position changes, and window coordinates as well.

Also:

  • Coordinates may be decimal fractions. That’s normal, internally browser uses them for calculations. We don’t have to round them when setting to style.position.left/top, the browser is fine with fractions.
  • Coordinates may be negative. For instance, if the page is scrolled down and the top elem is now above the window. Then, elem.getBoundingClientRect().top is negative.
  • Some browsers (like Chrome) provide additional properties, width and height of the element that invoked the method to getBoundingClientRect as the result. We can also get them by subtraction: height=bottom-top, width=right-left.
Coordinates right/bottom are different from CSS properties

If we compare window coordinates versus CSS positioning, then there are obvious similarities to position:fixed. The positioning of an element is also relative to the viewport.

But in CSS, the right property means the distance from the right edge, and the bottom property means the distance from the bottom edge.

If we just look at the picture above, we can see that in JavaScript it is not so. All window coordinates are counted from the upper-left corner, including these ones.

elementFromPoint(x, y)

The call to document.elementFromPoint(x, y) returns the most nested element at window coordinates (x, y).

The syntax is:

let elem = document.elementFromPoint(x, y);

For instance, the code below highlights and outputs the tag of the element that is now in the middle of the window:

let centerX = document.documentElement.clientWidth / 2;
let centerY = document.documentElement.clientHeight / 2;

let elem = document.elementFromPoint(centerX, centerY);

elem.style.background = "red";
alert(elem.tagName);

As it uses window coordinates, the element may be different depending on the current scroll position.