How to find screen size in JavaScript?

Today we will learn how to deal with the screen size in JavaScript. Sometimes there is a need to know the height or width of the device’s screen and the scenarios can be to hide/show any element or perform different click operation based on the screen size that could include opening a different popups/modals based on the screen size. We will learn about functions which returns the height or width of the screen based on the different aspects like the screen resolution, visible area etc.

There are different types of screen information user can find some are mentioned below:

  • The total screen size of device
  • The available screen size
  • The window inner height/inner width
  • The window outer height/outer width

The total screen size:

The total screen size can be found using window.screen function.

To find the height of the screen the function is: window.screen.height;

// This returns screen height in pixels.

To find screen width the function is: window.screen.width;

// This returns screen width in pixels.

Example code:

const h= window.screen.height; // Output: 864
const w = window.screen.width; // Output: 1536

The available screen size:

screen.availHeight

This returns available screen size in pixels by subtracting the user interface features displayed by the Operating system for example taskbar.

screen.availWidth

This returns how much horizontal space is available to the window in pixels

Example Code:

const height= window.screen.availHeight; // Output: 824
const width = window.screen.availWidth; // Output: 1536

The window inner height/inner width

The inner.height function returns the height of window area which is containing content.

Example code:

let height = window.innerHeight;

The inner.width function returns the width of window area which is containing content.

Example code:

let width = window.innerWidth;

The window outer height/outer width

The outerHeight returns the outer height of the window, including all interface elements (like toolbars/scrollbars).

Example Code:

let height = window.outerHeight;

The outerWidth returns the outer width of the window, including all interface elements (like toolbars/scrollbars).

Example Code:

let width = window.outerWidth;

Leave a Comment