How to detect the screen resolution with JavaScript?

How to detect the screen resolution with JavaScript?

Is there a way that works for all browsers?

Solutions/Answers:

Solution 1:

original answer

Yes.

window.screen.availHeight
window.screen.availWidth

update 2017-11-10

From Tsunamis in the comments:

To get the native resolution of i.e. a mobile device you have to multiply with the device pixel ratio: window.screen.width * window.devicePixelRatio and window.screen.height * window.devicePixelRatio. This will also work on desktops, which will have a ratio of 1.

And from Ben in another answer:

In vanilla JavaScript, this will give you the AVAILABLE width/height:

window.screen.availHeight
window.screen.availWidth

For the absolute width/height, use:

window.screen.height
window.screen.width

Solution 2:

var width = screen.width;
var height = screen.height;

Solution 3:

In vanilla JavaScript, this will give you the AVAILABLE width/height:

window.screen.availHeight
window.screen.availWidth

For the absolute width/height, use:

window.screen.height
window.screen.width

Both of the above can be written without the window prefix.

Like jQuery? This works in all browsers, but each browser gives different values.

$(window).width()
$(window).height()

Solution 4:

Do you mean display resolution (eg 72 dots per inch) or pixel dimensions (browser window is currently 1000 x 800 pixels)?

Related:  Find a value in an array of objects in Javascript [duplicate]

Screen resolution enables you to know how thick a 10 pixel line will be in inches. Pixel dimensions tell you what percentage of the available screen height will be taken up by a 10 pixel wide horizontal line.

There’s no way to know the display resolution just from Javascript since the computer itself usually doesn’t know the actual dimensions of the screen, just the number of pixels. 72 dpi is the usual guess….

Note that there’s a lot of confusion about display resolution, often people use the term instead of pixel resolution, but the two are quite different. See Wikipedia

Of course, you can also measure resolution in dots per cm. There is also the obscure subject of non-square dots. But I digress.

Solution 5:

Using jQuery you can do:

$(window).width()
$(window).height()

Solution 6:

You can also get the WINDOW width and height, avoiding browser toolbars and… (not just screen size).

To do this, use:
window.innerWidth and window.innerHeight properties. See it at w3schools.

Related:  Play an audio file using jQuery when a button is clicked

In most cases it will be the best way, in example, to display a perfectly centred floating modal dialog. It allows you to calculate positions on window, no matter which resolution orientation or window size is using the browser.