Good day, friends!
I present to you the translation of a short note “How to Get the Screen, Window, and Web Page Sizes in JavaScript” by Dmitri Pavlutin.
To determine the orientation of the browser window (landscape or portrait), you can compare its width and height.
However, it is easy to get confused with all the different sizes available: there are screen sizes, window sizes, web pages, etc.
What do these sizes mean and, most importantly, how to get them? This is what I'm going to talk about.
1. Screen
1.1. Screen size
Screen size is the width and height of the entire screen: monitor or mobile display.
You can get information about the screen size using the
screen
object property window
:
const screenWidth = window.screen.width
const screenHeight = window.screen.height
1.2. Available screen size
The available screen size is the width and height of the active screen without the operating system toolbar.
To get the available screen size, we again turn to
window.screen
:
const availableScreenWidth = window.screen.availWidth
const availableScreenHeight = window.screen.availHeight
2. Window
2.1. Outer window size (or outer window size)
The size of the external window is the width and height of the current browser window, including the address bar, tab bar and other browser panels.
You can get information about the size of the external window using the properties
outerWidth
and the outerHeight
object window
:
const windowOuterWidth = window.outerWidth
const windowOuterHeight = window.outerHeight
2.2. Inner window size (or inner window size)
The inner size of the window is the width and height of the viewport (viewport).
The object
window
provides properties innerWidth
and innerHeight
:
const windowInnerWidth = window.innerWidth
const windowInnerHeight = window.innerHeight
If we want to get the inner size of the window without scrollbars, we do the following:
const windowInnerWidth = document.documentElement.clientWidth
const windowInnerHeight = document.documentElement.clientHeight
3. Web page size
Web page size is the width and height of the displayed content (rendered content).
Use the following to get the size of your web page (includes page padding, but excludes borders, padding, and scroll bars):
const pageWidth = document.documentElement.scrollWidth
const pageHeight = document.documentElement.scrollHeight
If
pageHeight
greater than the inner height of the window, then a vertical scroll bar is present.
4. Conclusion
Hopefully now you understand how to get different sizes.
Screen size is the size of the monitor (or display), and the available screen size is the screen size without the OS toolbars.
The outer window size is the size of the active browser window (including the search bar, tab bar, open sidebars, etc.), and the inner window size is the size of the viewport.
Finally, the size of the web page is the size of the content.
Thank you for your attention, friends!