How to get the Width and Height of the screen in JavaScript?


In this article, we are going to discuss how to get the width and height of the screen in JavaScript.

Javascript provides an window.screen object that contains information regarding the user's screen. The information includes height and width, and also many other features.

To find the height and width of the screen you need to use the following read-only properties

  • Screen.height − This property is used to get the height of the screen in pixels.
  • Screen.width − This property is used to get the width of the screen in pixels.

Syntax

Following is the syntax of the height to get the height and with of a screen respectively −

screen.height;
screen.width;

Example 1

In the following example, the width of the screen is displayed using the screen.width method.

<html>
<body>
<p id="width"> </p>
   <script>
      document.getElementById("width").innerHTML =
      "Screen width is " + screen.width;
   </script>
</body>
</html>

Example 2

In the following example, the height of the screen is displayed using the screen.height method.

<html>
<body>
   <p id="height"> </p>
   <script>
      document.getElementById("height").innerHTML =
      "Screen heigth is " + screen.height;
   </script>
</body>
</html>

Example 3

In the following example we are trying to get the width and height of the screen using the screen.width and screen.height properties −

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Get the width and height of the screen</title>
      <div id="width"></div>
      <div id="height"></div>
   </head>
   <body>
      <script type="text/javascript">
         document.getElementById("width").innerHTML ="Width of the screen : " + screen.width;
         document.getElementById("height").innerHTML ="Height of the screen : " + screen.height;
      </script>
   </body>
</html>

Example 4

Following is another example of this −

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Get the width and height of the screen</title>
      <input type="button" onclick="getWidthLength()" value="click here to get the width and height"></inpu>
      <div id="width"></div>
      <div id="height"></div>
   </head>
   <body>
      <script type="text/javascript">
         let getWidthLength = function () {
            document.getElementById("width").innerHTML ="Width of the screen : " + screen.width;
            document.getElementById("height").innerHTML ="Height of the screen : " + screen.height;
         };
      </script>
   </body>
</html>

Updated on: 07-Dec-2022

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements