iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Screen

window.screen describes the physical display the browser is showing on — useful for adaptive layouts beyond viewport.

Properties

PropertyReturns
screen.width / heightTotal screen pixels.
screen.availWidth / availHeightMinus dock / taskbar.
screen.colorDepth / pixelDepthBit-depth (24 = 16M colours).
screen.orientationObject with type and angle.
window.devicePixelRatioPhysical-to-CSS pixel ratio (2 on Retina).

Better signals for layout

QuestionUse
How wide is the viewport?window.innerWidth or matchMedia — NOT screen.width
Should I serve a 2× image?window.devicePixelRatio >= 2 or srcset
Is the device in landscape?screen.orientation?.type.startsWith("landscape")
Coarse pointer (touch)?matchMedia("(pointer: coarse)").matches

Orientation change

JS
screen.orientation.addEventListener("change", () => {
  console.log("now", screen.orientation.type, screen.orientation.angle);
});
Privacy: screen properties are part of the browser fingerprinting surface. Don't read them unless you actually need them for layout.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Screen!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Detect a high-DPI display.

if (window. >= 2) loadRetinaImage();

Test yourself

Q1. For media-query-like layout decisions prefer…
Q2. High-DPI ratio is reported by…
Q3. Current orientation is on…

Discussion

Loading…