You can use the window.screen object in JavaScript to detect the screen resolution of a user’s device. The screen object has several properties that can be used to determine the screen resolution.

Here is an example of how to use the screen object to detect the screen resolution:

let width = window.screen.width;
let height = window.screen.height;
console.log("Screen resolution: " + width + " x " + height);

In the above code, the screen.width property returns the width of the screen in pixels, and the screen.height property returns the height of the screen in pixels.

You can also use the window.innerWidth and window.innerHeight properties to get the dimensions of the browser window.

let width = window.innerWidth;
let height = window.innerHeight;
console.log("Window resolution: " + width + " x " + height);

Please note that window.screen.width and window.screen.height will give you the resolution of the device’s screen, while window.innerWidth and window.innerHeight will give you the resolution of the browser window.

Also, you can use the window.devicePixelRatio to get the ratio of physical pixels to device-independent pixels which is a value that could be used to adjust your layout.

It’s worth noting that these properties work on all modern browsers, but they may not be supported on older browsers.

You can use any of these methods depending on your requirement.

Also Read:

Categorized in: