How to get clientWidth & clientHeight before the DIV is visible

I want to get the dimensions of the DIV element (used to display the popup menu at the cursor position), while style.display='none;' however DIV sizes always return 0. The only way, apparently, is to get the dimensions to make DIV style.display='block;' equal to 0.0, and then move it to the desired position, but it looks unstable.

I tried to make the DIV visible outside the visible area of ​​the screen, but this does not work. Is there a way to get clientWidth and clientHeight values ​​while the DIV is not hidden?

+7
javascript
source share
2 answers

If your DIV is not displayed, you will not be able to get its size.

However, there is a workaround. Your div should be “visible”, but this does not mean that its opacity and position should be 1 and relative.

Set the opacity to 0 and the position to “absolute,” and you can get the dimensions of the DIV.


EDIT

Since I think more people will have a similar problem, I feel I have to explain my answer a little more.

If you try to get the size of the hidden element with JavaScript, you will always get 0.

So, there are methods to get the real size without displaying the item to the user. My favorite is the one I wrote about above. Here are the more detailed steps:

  • you set the opacity of the elements to 0. Thus, it will not be displayed to the end user until you get the dimensions.

  • you set the position of the element to "absolute." Thus, it does not take up space.

  • it’s now safe to set the display to an “inline block”.

  • you read the sizes of the elements. This time you will get real values.

  • You will return to the “hidden” screen and set the opacity and position to their original values.

And now you have the size of the hidden element.

+10
source share

If you want to know the size of an element on the screen without visibility, you need it to be drawn on the screen, but not shown.

To get clientHeight and clientWidth, you need to visualize it so that calculations can be performed based on the current state of the screens (unless you have a pre-programmed width and height, which I assume you didn’t do)

You can find out more at MDN here

So you have options:

  • create your off-screen div using positioning ( fixed or absolute ) combined with z-index or opacity
  • use width: 0 and height: 0 and overflow: hidden , then use scrollHeight and scrollWidth to find the size of the overflow

choose which option is best for your site, considering things like responsiveness and screen overcharging and reviewing

+3
source share

All Articles