WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Detect Screen Resolution with JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the window.screen Object

You can simply use the width and height property of the window.screen object to get the resolution of the screen (i.e. width and height of the screen).

The following example will display your screen resolution on click of the button.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Screen Resolution Using JavaScript</title>
</head>
<body>
    <script>
    function getResolution() {
        alert("Your screen resolution is: " + screen.width + "x" + screen.height);
    }
    </script>
     
    <button type="button" onclick="getResolution();">Get Resolution</button>
</body>
</html>

To detect the native resolution of a mobile device display (e.g. retina display) you have to multiply the screen width and height with the device pixel ratio, like window.screen.width * window.devicePixelRatio and window.screen.height * window.devicePixelRatio.

The device pixel ratio tells the browser how many of the device's screen actual pixels should be used to draw a single CSS pixel. You can also use the following example to find the screen resolutions of desktops. Desktops screens generally have a device pixel ratio of 1:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Screen Resolution of Mobile Devices with JavaScript</title>
</head>
<body>
    <script>
    function getResolution() {
        alert("Your screen resolution is: " + window.screen.width * window.devicePixelRatio + "x" + window.screen.height * window.devicePixelRatio);
    }
    </script>
     
    <button type="button" onclick="getResolution();">Get Resolution</button>
</body>
</html>

See the tutorial on JavaScript window screen to learn about the other properties of screen object.


Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties