Signup/Sign In

How to detect screen resolution with JavaScript?

To get the screen resolution, we will use two properties, i.e., width and height of the window. screen object and window. inner object.

Let us now look at the example of how this is going to be executed.

var width = window.innerWidth;  //for width
var height = window.innerHeight; //for height

In the above example, we can see how to get the width and height of the screen using window.innerWidth and window.innerHeight.

Let us now see the two different approaches to print the screen resolution:

  1. Using window.inner object

  2. Using window.screen object

Let us now look at all the approaches one by one.

Example 1: Using window.inner object

This example will have HTML, CSS, and js combined to procure the output.

The inner property is used in this approach window. It refers to the window's inner width and height, or more precisely, the viewport (not including toolbars, window chrome, etc.; but including the space occupied by the vertical scrollbar, if any).

Let us now see the coding part for better understanding:

The example displays the browser window's height and width: (NOT including toolbars/scrollbars)

<!DOCTYPE html>
<html>
  <body>
    <h3>Get the size of the current screen/window</h3>
    <p id="js1"></p>
    <script>
      var width = window.innerWidth;
      var height = window.innerHeight;
      var result = document.getElementById("js1");
      result.innerHTML = "Browser width: " + width + ", height: " + height + ".";
    </script>
  </body>
</html>


Get the size of the current screen/window
Browser width: 1467, height: 615.

Example 2: Using window.screen object

In this example, window. screen object is used. If your screen contains a resolution of 2600x900, screen, the breadth can invariably be 2600.

Here, a button is created "Resolution", once clicked a prompt message will be there showing the resolution of your screen:

<!DOCTYPE html>
<html lang="en">
<head>

<title>Get Screen Resolution</title>
</head>
<body>
    <script>
    function Resolution() {
        alert("Screen resolution is: " + screen.width + " x " + screen.height);
    }
    </script>     
    <button type="button" onclick="Resolution();">Resolution</button>
</body>
</html>

Output:

prompt

Conclusion

In this tutorial, we use JavaScript to detect the screen resolution. We have use width and height to get screen resolution with help of two different methods. The first method is window.inner and the second method is window.screen.



About the author: