Q:

How to Detect Screen Resolution with JavaScript

0

How to Detect Screen Resolution with JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Parse JSON in JavaScript... >>
<< How to Include a JavaScript File in another JavaSc...