javascriptdom

Is the DOMRect from .getBoundingClientRect() live or immutable?


Let's say I get a DOMRect object from calling .getBoundingClientRect on an element:

let domRect = el.getBoundingClientRect();

If I keep this object around and the bounding rectangle of el changes (for example because its contents are updated, or because the user scrolls), which of the following is true?

  1. The domRect object reflects the new bounds of el. That is, it's a live view of the state of the DOM. Or:
  2. The domRect object reflects the original bounds of el. That is, it's an immutable snapshot of when el.getBoundingClientRect() was called.

Solution

  • The DOMRect object returned by el.getBoundingClientRect() is an immutable snapshot of the element's state at the exact time that .getBoundingClientRect() was called. It does not subsequently get updated by the browser, even if the page's layout changes of the user scrolls.

    Here's a CodePen to test this.

    The relevant spec is CSSOM View Module, which says (thanks @C3roe for finding this):

    NOTE: The DOMRect object returned by getBoundingClientRect() is not live.