JavaScript Window



The Browser Object Model (BOM) gives JavaScript the ability to "talk" to the browser.


Browser Object Model (BOM)

Browser Object Model (Browser ObjectModel (BOM)) There is no formal standard.

Methods and properties are often considered BOMs since modern browsers have implemented (almost) the same methods and properties for JavaScript interactivity.


Window object

All browsers support the window object. It represents the browser window.

All JavaScript global objects, functions, and variables automatically become members of the window object.

Global variables are properties of the window object.

Global functions are methods of the window object.

Even the document of HTML DOM is one of the attributes of the window object:

window.document.getElementById("header");

Same as this:

document.getElementById("header");


Window size

There are three ways to determine the size of the browser window (the browser's viewport, not the including toolbars and scroll bars).

For Internet Explorer, Chrome, Firefox, Opera and Safari:

  • window.innerHeight - The inner height of the browser window

  • window.innerWidth - The inner width of the browser window

For Internet Explorer 8, 7, 6, 5:

  • document.documentElement .clientHeight

  • document.documentElement.clientWidth

or

  • document.body.clientHeight

  • document.body.clientWidth

Practical JavaScript solution (covering all browsers):

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p id="demo"></p>
<script>
var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h=window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
x=document.getElementById("demo");
x.innerHTML="浏览器window宽度: " + w + ", 高度: " + h + "。"
</script>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance

This example displays the height of the browser window and width: (excluding toolbars/scrollbars)


Other Window methods

Some other methods:

  • window.open( ) - Open a new window

  • window.close() - Close the current window

  • window.moveTo() - Move the current window

  • window.resizeTo() - Adjust the size of the current window