How to detect the screen resolution with JavaScript?
You can easily detect the screen resolution with window.screen.width
for width and window.screen.height
for height:
This outputs the resolution as width by height, giving you the overall screen resolution in a convenient format.
Crucial Bifurcations: Absolute Dimensions vs. Available Screen
Getting absolute screen size
The variables totalWidth
and totalHeight
fetch the absolute dimensions of your screen, akin to asking a monitor "How big are you in pixels, honestly?".
Deriving available screen size
But, how about the usable screen space? Well, availWidth
and availHeight
play this role:
Mobile Devices & Their Fond love for Pixel Ratio
If you're dealing with mobile devices, pixel density affects screen resolution, like when your phone brags about the super retina display!
Here, devicePixelRatio
handles differences between CSS pixels and device pixels, great when you need accurate screen information for media queries or responsive design.
Understanding Viewport Dimensions
Sometimes, what matters is not the entire screen but the part of it where your web page is visible, which is our good ol' viewport:
These little fellows return the viewable area, unobstructed by browser toolbars and scrollbars. A classic case of "I'm here only for the content, ads you can keep to yourself!".
From 10,000 Feet: Other Aspects of Screen Resolution
Web designers make an assumption on a standard 72 dpi resolution. However, Javascript doesn't provide a physical resolution, only the pixel count, crucial for responsive designs.
Do note, non-square pixels, although rare, aren't considered in JavaScript resolution detection. Plus, the physical screen size remains unknown to your browser and JavaScript.
For jQuery users, $(window).width()
and $(window).height()
can be used to offer similar functionality.
Was this article helpful?