1

[JavaScript] Width of Browser Window in Pixel

 2 years ago
source link: http://siongui.github.io/2012/09/16/javascript-width-of-browser-window-in-pixel/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[JavaScript] Width of Browser Window in Pixel

Updated: February 26, 2015

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

<!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%"> </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>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK