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()?

auto
  • 1,062
  • 2
  • 17
  • 41
  • 1
    Does this answer your question? [Get the window height](https://stackoverflow.com/questions/3012668/get-the-window-height) – Ed Lucas Feb 13 '20 at 19:34
  • 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. – auto Feb 13 '20 at 19:54

2 Answers2

7

console.log('Window height',window.screen.height);
console.log('Inner height',window.innerHeight);
dota2pro
  • 7,220
  • 7
  • 44
  • 79
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
);
Richard
  • 101
  • 7
  • `document.body` height is not necessarily the same as the window height. – Teemu Feb 13 '20 at 19:41
  • In different browsers, this value may differ. – Richard Feb 13 '20 at 19:47
  • Or we can use only document.body.scrollHeight | document.documentElement.scrollHeight... This will be return a height with scroll.. – Richard Feb 13 '20 at 19:55
  • `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? – auto Feb 13 '20 at 20:08
  • 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.. – Richard Feb 13 '20 at 20:39
  • 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 window – Richard Feb 13 '20 at 20:46