1

Is there a way to get the width and height of the page viewport NOT the contents of a page without setting the body width and height to 100%?

The answers I've found require the html and body elements to be set to 100% width and 100% height.

I already have content on the page that sometimes extends beyond the viewport size. I can't switch the body to 100% and then check the values and then revert back.

In my opinion there should be a property that is simply:

document.body.viewportWidth;
document.body.viewportHeight;

That update on window resize and exclude the chrome.

There are related questions here:

HTML5 Canvas 100% Width Height of Viewport?

Update:
I've been using this:

var availableWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var availableHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

It might be that the viewport values are correct but the element itself is growing or shrinking.

I can't find the document.documentElement.clientWidth or document.documentElement.clientHeight in the documentElement docs though.

Update 2:
It looks like it might be an error on my part. I noticed in the logs that occasionally the element has no computed width or height possibly because it hasn't been added to the page yet.

var elementWidth = parseFloat(getComputedStyle(element, "style").width);
var elementHeight = parseFloat(getComputedStyle(element, "style").height);

I think the code I'm already using above is correct.

Update 3:
I found this page on getting the viewport size.

1.21 gigawatts
  • 12,773
  • 23
  • 85
  • 187
  • 1
    clientWidth and clientHeight are defined in the [CSSOM View spec](https://drafts.csswg.org/cssom-view/#dom-element-clientwidth) On the documentElement is gives the viewport dimensions minus any scrollbars. – Alohci Dec 06 '19 at 18:55
  • 1
    window.innerWidth and innerHeight are also defined there. They give the viewport dimensions including any scrollbars. – Alohci Dec 06 '19 at 19:02

3 Answers3

4

I may not understand your question correctly, but if you're looking for the height and width of the browser window, you could use window.innerHeight and window.innerWidth.

Here is some more information on the window height and width that could be useful.

1

Does this help?

document.documentElement.clientWidth
document.documentElement.clientHeight
Ricardo Gonzalez
  • 1,590
  • 1
  • 10
  • 22
JMRC
  • 1,336
  • 16
  • 34
1

Does window.innerWidth and window.innerHeight work for you?

RevelMind
  • 99
  • 5