How to Detect Screen Resolution with JavaScript
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.
Example
function getResolution()
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:
Example
function getResolution()
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:
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:
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)
Get the size of the current screen/window
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 2600×900, 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:
function Resolution()
Output:
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.