How to get the width of device screen in JavaScript ?
Last Updated :
20 Jun, 2023
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;" >
GeeksforGeeks
</ 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 >
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;" >
GeeksforGeeks
</ 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 >
let elm = document.getElementById("GFG");
function GFG_Fun() {
elm.innerHTML = document.
documentElement.clientWidth + " pixels";
}
</ script >
</ body >
</ html >
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...