[JavaScript] Width of Browser Window in Pixel


Here is an interesting and sometimes practical question:

How do I get the width of browser window in pixel?

The answer is easy: add a div element right after the body tag, make it 100% wide, and get the offsetWidth property of the div.

Demo

Source Code for Demo:

getWindowWidthPixel.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>[JavaScript] Width of Browser Window in Pixel</title>
</head>
<body>

 <div id="width" style="width: 100%">&nbsp;</div>
 <div id="info"></div>

<script type="text/javascript">
  var width = document.getElementById("width").offsetWidth;
  document.getElementById('info').innerHTML = 'The width of browser window is ' + width + ' pixels.';
  document.getElementById("width").parentNode.removeChild(document.getElementById("width"));
</script>
</body>
</html>