Finding height() of window in Vanilla JavaScript
Asked Answered
O

2

6

I am trying to write a program in pure, vanilla JS. I must find the height and width of the window. In JQuery I use .height(). Online search shows that clientHeight or innerHeight is supposed to be the equivalent to height() however in my program $(widow).height() and window.innerHeight console-log different values for both (4500 for height() and 440 for innerHeight..and undefined for window.clientHeight)

How can I find the Vanilla JS equivalent to $(widow).height()?

Overbuild answered 13/2, 2020 at 19:28 Comment(2)
Does this answer your question? Get the window heightSubstance
Thanks. Though as I said in the post, innerHeight is returning a different value than height(), however document.documentElement.offsetHeight seems to work. Though the answer says that is for older browsers so I'm wondering why these values are different and if it really is the best solution.Overbuild
C
8

console.log('Window height',window.screen.height);
console.log('Inner height',window.innerHeight);
Cinch answered 13/2, 2020 at 19:30 Comment(0)
S
3

The full height with scroll

const height = Math.max(
  document.body.scrollHeight, document.documentElement.scrollHeight,
  document.body.offsetHeight, document.documentElement.offsetHeight,
  document.body.clientHeight, document.documentElement.clientHeight
);
Shogun answered 13/2, 2020 at 19:37 Comment(6)
document.body height is not necessarily the same as the window height.Shaunteshave
In different browsers, this value may differ.Shogun
Or we can use only document.body.scrollHeight | document.documentElement.scrollHeight... This will be return a height with scroll..Shogun
document.documentElement.offsetHeight seems to work. Can you elaborate why this work, and/or why I'd need to try three approaches and select the highest one?Overbuild
You should use max value because some browsers can have different values. Example : in opera version x.x.x we have clientHeight > scrollHeight or etc.. but in newest version of opera all good... This code save you from unexpected behaviors of all versions from different browsers..Shogun
It works because for example: you have window height 500px, but you have more content than 500px and you have scroll, so you need get full value of document with scroll and not value of windowShogun

© 2022 - 2024 — McMap. All rights reserved.