GetBoundingClientRect for Visibility Detection

Background : I am currently working on a project in which my JS application is embedded in several other (parent) JS applications. Some parent application can show / hide my application by setting the display to: block / none for any element containing my application. Other parent applications temporarily remove my application from the DOM and attach it later. Few parent applications use shadow storage, so I don’t have access to items in the parent application.

I need a way to check if my application is visible (it is visible inside the DOM, do not care about visibility: it is hidden and should not be inside the viewport) without changing the parent applications, so I looked at getBoundingClientRect.

Question : At least on chrome, getBoundingClientRect returns (w: 0, h: 0, l: 0, t: 0) if the element or its ancestor has the mapping: none or if it is removed from the DOM. I could not find documentation to guarantee this behavior, and I wonder if it is safe (in the sense that this logic will not change) to use getBoundingClientRect to check the visibility of an element.

I also need to know if this behavior is compatible in all major browsers, including FF, IE8 + and Safari. Is it documented anywhere?

Finally, why (0,0,0,0)? I feel that getBoundingClientRect should return null in cases where (0,0,0,0) actually means something else. Is there a good reason for this?


Edited / additional question : Thanks to istos for indicating that returning null could violate some unsuspecting code, for example:

console.log(clientRectObject.height); // TypeError: Cannot read property 'height' of null 

Do not complain about the current behavior, but as a design question: instead of null, can it be a more useful alternative to return incorrect Rect values ​​(such as negative width and height)?

+5
source share
1 answer

First, I would like to learn how popular libraries like jQuery solve a similar problem. Here are some links to jQuery source:

Next, I will search the Internet for any tips, including MDN:

Unfortunately, the best way to check if the behavior of getBoundingClientRect same in most browsers is to actually test inside these browsers. If you do this, go back to MDN and add your results.


It seems to me that getBoundingClientRect should return null in such cases

Although returning zero in such cases seems logical, it is actually not ideal, because usually it returns a ClientRect object with the properties of the upper, right, lower, left, width and height levels and the code how it will break:

 console.log(clientRectObject.height); // TypeError: Cannot read property 'height' of null 

In other words, the API will not match this way.

+3
source

Source: https://habr.com/ru/post/1212565/


All Articles