Steven Lu
Steven Lu

Reputation: 43427

Why are certain JavaScript objects magical?

Try this, right here, from Safari or Chrome or what have you, in the inspector's JS console.

var x = document.body.getBoundingClientRect();
> undefined

x.top;
> 0

x.top += 5;
> 5

x.top;
> 0

I had expected the object produced by getBoundingClientRect() to be a modifiable object. I have just shown this to be false. Neither does it stay in sync with the state of the browser, so if I scroll the page a bit, then check the value of x.top, it still reports 0 even though it should now be a negative value since I've scrolled down. At least, if I reassign x with another call to getBoundingClientRect() it would then report a negative value.

So, it doesn't respond to me trying to change it, but there doesn't appear to be some higher purpose to exhibiting that behavior.

Maybe there's some sort of clean way to explain this? Something better than *shrug* that's what it does.

Upvotes: 2

Views: 363

Answers (2)

Bergi
Bergi

Reputation: 664528

The getBoundingClientRect method does return a ClientRect object whose properties are specified to be read-only. That's just how it works :-) Most browsers will implement this as a property with a writable: false descriptor (but don't trust this, host objects may be implemented arbitrarily).

The higher purpose of this behaviour is that the method will return a static snapshot of the current values, which is detached from the live DOM and the changes made to it. The returned object is frozen therefore, and assigning to it does not make sense - there are other methods for changing the view.

Upvotes: 4

Oriol
Oriol

Reputation: 288120

According to https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect,

rectObject = object.getBoundingClientRect();

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

And according to https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIDOMClientRect,

the attributes of the TextRectangle returned are Read only.

Moreover, the specification (http://www.w3.org/TR/cssom-view/#the-clientrect-interface) says

interface ClientRect {
   readonly attribute float top;
   readonly attribute float right;
   readonly attribute float bottom;
   readonly attribute float left;
   readonly attribute float width;
   readonly attribute float height;
};

Upvotes: 4

Related Questions