How to Detect Screen Resolution with JavaScript

  102 views   2 months ago Javascript

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>

 

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles