Home /JavaScript/Window Object

Window Object

The JavaScript window object has quite a few properties and methods, but beware because many of them are not supported in all major browsers. However, the information you can obtain using the window object can be extremely important depending on what you want to do. For example, maybe for some reason you want to know the size of the user's window. Using the window object is the primary way you would get this information.

The JavaScript window object isn't used very often, but it is quite powerful. For example, one of the window object's methods is a print(). So, you could create a button on the page that would trigger an event that called the window.print() rather than the user having to search in the browser for the hidden print option. One cool distinction about the window that you may notice is that you can directly type something like alert() and not window.alert() and JavaScript will completely know what you are talking about. That is because window is the primary object of a browser, which means you don't need to declare it before the method unlike the other objects.

Common Window Object Properties

innerHeight – gets or sets the inner height of the actual content area

document.write(window.innerHeight);
Result: 839

innerWidth – gets or sets the inner width of the actual content area

document.write(window.innerWidth);
Result: 1446

outerHeight – gets or sets the outer height of a window

(This includes tabs, toolbars, and scrollbars)

document.write(window.outerHeight);
Result: 960

outerWidth – gets or sets the outer width of a window

(This includes tabs, toolbars, and scrollbars)

document.write(window.outerWidth);
Result: 1446

Common Window Object Methods

  • alert() – shows an alert box
  • print() – prints the window's contents
  • scrollTo() – scrolls to specified coordinates

Print Example

function exampleFunction3() { 
    window.print();
}
<input name="" type="button" onclick="exampleFunction3()" value="I Print"/>

Scroll Example

function exampleFunction4() {
    window.scroll(0,30)
}
<input name="" type="button" onclick="exampleFunction4()" value="I Scroll"/>

Timers

Timers are a method of the window object. They can be very tricky, but often very useful when dealing with a variety of issues. While a good amount of timers are used correctly, JQuery's animate can often do your job much more efficiently. Please be sure to check out a few of JQuery's functions before using timers.

var timeoutTimer = setTimeout("alert('10 seconds!')", 30000); // This fires once
var intervalTimer = self.setInterval("intervalTimerFunction()", 10000); // This fires every 10 seconds

function intervalTimerFunction() // intervalTimer calls this function {
    alert('intervalTimer timer happened');
}

<input name="" type="button" onclick="clearTimeout(timeoutTimer)" value="Stop timeoutTimer"/>
<input name="" type="button" onclick="clearInterval(intervalTimer)" value="Stop intervalTimer"/>