Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to get the width of device screen in JavaScript ?

How to get the width of device screen in JavaScript ?

Given an HTML document that is running on a device and the task is to find the width of the working screen device using JavaScript

Example 1: This example uses window.innerWidth to get the width of the device screen. The innerWidth property is used to return the width of the device. 

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        How to get the width of device
        screen in JavaScript?
    </title>
</head>
 
<body style="text-align: center;">
    <h1 style="color:green;">
        neveropen
    </h1>
 
    <h3>
        Click on Button to Get the
        Width of Device's Screen
    </h3>
 
    <button onclick="GFG_Fun()">
        Click Here
    </button>
 
    <p id="GFG"></p>
 
    <!-- Script to display the device screen width -->
    <script>
        let elm = document.getElementById("GFG");
 
        function GFG_Fun() {
            let width = window.innerWidth;
            elm.innerHTML = width + " pixels";
        }
    </script>
</body>
 
</html>


Output:

 

Example 2: This example uses document.documentElement.clientWidth method to get the width of device screen. 

html




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        How to get the width of device
        screen in JavaScript?
    </title>
</head>
 
<body style="text-align: center;">
    <h1 style="color:green;">
        neveropen
    </h1>
 
    <h3>
        Click on Button to Get the
        Width of Device's Screen
    </h3>
 
    <button onclick="GFG_Fun()">
        Click Here
    </button>
 
    <p id="GFG">
    </p>
 
    <!-- Script to display the device screen width -->
    <script>
        let elm = document.getElementById("GFG");
 
        function GFG_Fun() {
            elm.innerHTML = document.
                documentElement.clientWidth + " pixels";
        }
    </script>
</body>
 
</html>


Output:

 

RELATED ARTICLES

Most Popular

Recent Comments