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:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
20 Jun, 2023
Like Article
Save Article