What You Need To Know JavaScript Window Screen Object

Posted by TotalDC

Previously we checked JavaScript window object and in this tutorial, you will learn about JavaScript window screen object.

What Is The Screen Object In JavaScript

Simply the window.screen is an object that contains information about the user’s screen for example resolution, color depth, pixel depth etc.

The window object is at the top of the scope chain, so properties of the window.screen object can be accessed without specifying the window. For example instead of window.screen.width you can simply use screen.width. The following section will explore how to get information on the user’s display using the screen object.

How To Get Width And Height Of The Screen In JavaScript

For this, you can use the screen.width and screen.height properties that obtain the width and height of the user’s screen in pixels. Here’s an example:

<script>
function getResolution() {
    alert("Your screen is: " + screen.width + "x" + screen.height);
}
</script>
 
<button type="button" onclick="getResolution();">Get Resolution</button>

How To Get Available Width And Height Of The Screen In JavaScript

For this, you need to use screen.availWidth and screen.availHeight properties that will get the width and height available to the browser in pixels.

The screen’s available width and height are equal to the screen’s actual width and height minus the width and height of interface features like the taskbar in Windows. Here’s an example:

<script>
function getAvailSize() {
    alert("Available Screen Width: " + screen.availWidth + ", Height: " + screen.availHeight);
}
</script>
 
<button type="button" onclick="getAvailSize();">Get Available Size</button>

How To Get Screen Color Depth In JavaScript

If you want to get the color depth of the user’s screen, you can use the screen.colorDepth property. Color depth is the number of bits used to represent the color of a single pixel. Color depth indicates how many colors a device screen is capable of producing. For example, a screen with a color depth of 8 can produce 256 colors (28). Here’s an example:

<script>
function getColorDepth() {
    alert("Your screen color depth is: " + screen.colorDepth);
}
</script>
 
<button type="button" onclick="getColorDepth();">Get Color Depth</button>

How To Get Screen Pixel Depth In JavaScript

You can get the pixel depth of the screen using the screen.pixelDepth property. Pixel depth is the number of bits used per pixel by the system display hardware. Keep in mind that for modern devices, color depth and pixel depth are equal. Here’s an example:

<script>
function getPixelDepth() {
    alert("Your screen pixel depth is: " + screen.pixelDepth);
}
</script>
 
<button type="button" onclick="getPixelDepth();">Get Pixel Depth</button>