JavaScript Window Object

JavaScript Window – The Browser Object Model

The Browser Object Model shortly refer as BOM allows JavaScript to interact with Browser(Window Object).

The Browser Object Model

There is no any specific official standard for the Browser Object Model(BOM).

Since all modern browsers have almost the same standards(methods and properties) to JavaScript interactivity, it is refer to the properties of BOM.

The Window Object

All browser has support for Window object. It refer to the current open browser’s window.

The Window object is parent of all, so all global JavaScript functions, methods, variables and objects automatically become member of Window object.

All global variables becomes properties of a Window.

Same applies to global methods and functions, they become methods of window.

There is only one instance of Window object at a time.

The window object is top of all objects, even Document object (DOM) is also property of it.

window.document.getElementById("header");

Above statement can be rewrite as

document.getElementById("header");

Often window word is ignored from the statements as shown above.

Window Size

You can get size(width and height) of window using window object.
There are two properties which can be used to get window size.

Both properties to get window size returns size in pixels.

  • window.innerHeight – inner height of the browser window (in pixels)
  • window.innerWidth – inner width of the browser window (in pixels)

Both properties ignore window toolbar and window scroll-bar height & width as its not part of window view-port.

For old versions of Internet explorer 5,6,7,8 there are different properties

  • document.documentElement.clientHeight
  • document.documentElement.clientWidth

or

  • document.body.clientHeight
  • document.body.clientWidth

Below example illustrates browser independent height and width of window.

Example

<!DOCTYPE html>
<html>
<body>

<p id="text"></p>

<script>
var ww = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var wh = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

document.getElementById("text").innerHTML = "Browser window dimention width: " + ww + ", height: " + wh + ".";
</script>

</body>
</html>

Download the code Run the code

Above example displays the browser window’s height and width. Try it resizing browser to see different results.

Other Window Methods

Below are some other window methods.

  • window.open() – open a new window
  • window.close() – close the current window
  • window.moveTo() -move the current window
  • window.resizeTo() -resize the current window
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .