TOC

The community is working on translating this tutorial into Spanish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

JavaScript for Web: The BOM:

The Window object

In our introduction to JavaScript for the web, we briefly discussed the Window object and how it acts as the "global object" of JavaScript when running in a webbrowser. A global object is basically the top of the hierarchy, allowing you to access everything relevant for your JavaScript code:

It also means that every variable you declare is added to the window object, where you can find it again, as illustrated by this little example:

var myVariable = "Hello, world!";
alert(window.myVariable);

Notice that I use the var keyword to declare this variable. If you use the more modern let keyword to declare the variable, it won't be added to the window object. This is by design.

Functions are added to the window object as well:

function HelloWorld()
{
	alert("Hello, world!");
}

window.HelloWorld();

But since window is the global object, it also means that unless you specifically reference another object, JavaScript will assume that you are trying to reach something made available by the window object. Therefore you are free to omit the "window." prefix in the above examples, just like I did when I used the alert() method, which is also declared on the window object. In other words, the last two lines of this example will accomplish the exact same thing:

var myVariable = "Hello, world!";
window.alert(window.myVariable);
alert(myVariable);

With these basic details about the window object covered, I would like to move on to talking about the properties and methods that you'll find on this object. This will not be a complete list, because the window object comes with a LOT of functionality, but we'll cover all the most interesting properties and methods. For the full list, please see the documentation.

Window properties

The window object comes with several interesting properties, but many of them are complex properties (objects) and not just simple types like strings or numbers. For instance, you'll find properties like history and location, which them selves contains several interesting properties and methods, so we'll dedicate entire articles to these objects within this chapter. For now, let's discuss the simple properties found on the window object.

window.frames

This property is an array-like object containing references to all frames on the page. The traditional frames (from the FRAME HTML tag) are not used a lot anymore, but it also includes iframes (from the IFRAME tag). It allows you to iterate through all the frames/iframes and obtain information or manipulate each of them.

window.innerHeight / window.innerWidth

With these two properties, you can easily obtain the dimensions of the viewport, which is basically the space available to the content of the page within the browser window. These properties are read-only, so you can't use them to change the size of the window, but they can help you figure out how much space you have available and use these numbers for various calculations etc. Here's a simple example:

alert("Inner window size: " + window.innerWidth + " x " + window.innerHeight);

window.opener

A window can open another window, usually in the form of a popup window. In case this newly opened window need to reference the window that opened it, e.g. to return a user-specified value, the window.opener property will contain a reference to the opener of the current window.

If the window was not opened by another window, or if the origin of the opener is not the same as the actual window, there are several limitations to what you can do. Please see the documentation for the full set of rules.

window.outerHeight / window.outerWidth

You can use window.innerWidth and window.innerHeight to get the size of the layout viewport, but if you're looking to get the full size of the complete browser window, you need to use the outerWidth/outerHeight properties. Here's a simple example:

alert("Outer window size: " + window.outerWidth + " x " + window.outerHeight);

window.screenX / window.screenY

Use these two properties to get the position of the browser window relative to the screen. The screenX property will return the distance, in CSS pixels, between the left border of the browser to the left part of the screen, and the screenY property will return the distance from the top part of the browser to the top of the screen.

Here's an example - try moving your browser window around and then run it multiple times:

alert("Window position: " + window.screenX + " x " + window.screenY);

Please notice that these properties will accomplish the same as the screenLeft and screenTop properties, which was implemented in Internet Explorer only to begin with, but later added as aliases to screenX and screenY due to popularity.

window.scrollX / window.scrollY

Use these properties to figure out how far the document has been scrolled within the viewport of the browser. Initially, they will both return 0, but as soon as you start scrolling in the document, they will increase, depending on the direction that you scroll. scrollY will return the vertical distance scrolled from the top, while the scrollX property will return the horizontal distance scrolled from the left. Here's an example - try scrolling on this page and then run it multiple times:

alert("Scroll position: " + window.scrollX + " x " + window.scrollY);

Window methods

With the most interesting properties covered, let's talk about the most interesting methods that you'll find on the window object.

window.alert()

This method will simply display a message to the user, usually in the form of a popup window. This can be a bit annoying to the end-user, and each browser may choose how this popup looks, so its not considered a user-friendly way to interact with the user. You will see it used a LOT in this tutorial though, to easily illustrate the result of our example code, since its so simple and straight-forward to use, as we can see from this example:

window.alert("Hello, world!");

In general, you should mostly use this for testing stuff out. If you want to convey something real to the user, consider alternative ways that will integrate more seamlessly with the rest of your user interface.

window.close()

The window.close() can close a window, but only if this window was created by the same web page using the window.open() method, used a lot to create popup windows. If you want an example, check out the one I created for window.open() below.

window.confirm()

While alert() will give you a dialog/prompt with only one option ("Ok"), the confirm() method allows the user to either accept or deny the proposed action. This is useful in a lot of situations, e.g. to allow the user to confirm a delete action. The method will return true if the user accepts ("Ok") or false if the user denies ("Cancel"). Here's an example:

if(confirm("Are you sure that you wish to delete this item?"))
	alert("Item deleted!");
else
	alert("Okay, no problem, the item was NOT deleted!");

window.moveBy() / window.moveTo()

These two methods allow you to move the window around on the screen. Or, they used to, because since this was heavily abused to annoy or even trick the user, this has been restricted a LOT by most modern browsers. Generally they only allow you to move a window that was created by the window.open() method, and only if this window is not opened as a tab in the browser, but as a stand-alone window or popup.

The window.moveBy(x, y) method will move the window relative to its current position, while the window.moveTo(x, y) will move the window to an absolute position on the screen. Because of all the restrictions, these methods are no longer terribly useful, but I'll show you how window.moveBy() can be used in the example for window.open() below.

window.open()

The window.open() method allows you to open a new window. It allows for several useful parameters to control how the window is opened and which content it should contain (if any). I'll show you an example where we use some of these features, but for the full list, please have a look at the documentation.

Important notice: Because of too much abuse of popup windows in the past, most browsers will impose several restrictions on what you can do with windows. For instance, most browsers will, by default, prevent you from opening a new window, especially if its in the form of a popup. The user is normally asked, although often in a very subtle way, if they want to allow the opening of a new window/popup. So, for the below example to work, please allow the popup in your browser.

As promised, here's an example where I use the window.open() method in combination with the moveBy() and close() methods. Using two timers, I first move the window and then close it again, all within 5 seconds, to demonstrate how these methods work in one example:

let wnd = window.open("/", "wnd", "popup=true,width=400,height=600");

window.setTimeout(function()
{
	wnd.moveBy(200, 50);
}, 2000);

window.setTimeout(function()
{
	wnd.close();
}, 5000);

Notice the parameters I use for the open() method: The first is the URL I want loaded in the new window, in this case, just the index of this website. The second parameter is a target, which is not really relevant in this example. In the third parameter, I can specify options for the new window, in the form of a comma-separated option=value string. As you can see, I use this to specify that I want the new window to be a popup and then I specify a width and a height for it. For a full list of options, check the documentation.

As soon as the popup has been opened, I set two timers: One for 2 seconds, which I use to demonstrate the window.moveBy() method, and another timer for 5 seconds, which I use to demonstrate the window.close() method. Try running the example and make sure to tell your browser to allow the popup (you may have to re-run the example after allowing the popup).

window.prompt()

The prompt() method is a bit like the alert() and confirm() methods, but here you are allowed to ask the user for text input and then do something with the response. Let's quickly see how it works and then discuss the details afterwards:

let name = window.prompt("What's your name?");
alert("Hello " + name + " - nice to meet you!");

As you can see, in its basic form, it just takes a single parameter with instructions to the user about what kind of information you're looking for. In this case, we ask for the name and then assign it to a variable.

As a nice little extra feature, the prompt() method accepts a second parameter, which will add a default value to the input box. Try this modified example, where we suggest that the name of the user is "John Doe", while still allowing them to change this into something else:

let name = window.prompt("What's your name?", "John Doe");
alert("Hello " + name + " - nice to meet you!");

window.resizeBy() / window.resizeTo()

These methods will allow you to resize a window. However, just like the move* methods, the resize* methods have been heavily restricted to prevent abuse. So they can only be used for windows opened by the open() method, and you even have to add the resizable parameter when opening it. Here's a quick example:

let wnd = window.open("/", "wnd", "popup=true,width=400,height=600,resizable=true");

window.setTimeout(function()
{
	wnd.resizeTo(600, 400);
}, 2000);

Remember that you have to allow popups for this example to work.

In this example, we us the resizeTo() method, to resize the window to an absolute size. We could have used the resizeBy() method instead, if we wanted to resize the window relative to its existing size.

window.scroll() / window.scrollBy()

With these methods, you can control the scrollbars of the browser. This might not sound terribly useful, but it really is. For instance, you can scroll to a specific area or even element when you want to let the user know where they should be focusing.

First, lets have a look at the most basic version, the window.scroll() method. It allows you to scroll to an absolute position on the page, by specifying top and left coordinates. Generally, you will probably mostly be scrolling up and down (vertically), so we'll focus on the top parameter:

window.scroll(0, 200);

This simple example will simply scroll the page to 200 pixels from the top and 0 pixels from the left. In other words, the parameters to this method are in absolute values. If you want to scroll relatively to the current position, just use the scrollBy() method:

window.scrollBy(0, -300);

Notice that I specify a negative value, to scroll up instead of down. This example will scroll the page 300 pixels up from the current position.

Please notice that instead of specifying top and left parameters to these methods, you can provide a dictionary of the values. This will allow you to also specify the behavior when scrolling, which at the moment can be either smooth or instant. Notice the difference between these two examples:

Smooth scrolling:

window.scroll({ top: 0, behavior: "smooth"});

Instant scrolling:

window.scroll({ top: 0, behavior: "instant"});

Both examples will take you to the top of this page, but the smooth version will do it in an animated way, which can be less confusing to the user, but it will also take longer for large pages.

Summary

The Window object is one of the most important parts of the JavaScript DOM when working with JavaScript in a webbrowser. Because it's a global object, you might even be using it without realizing, as illustrated in this article.

We have only worked with some of the most useful properties and methods of the Windows object in this article - you should definitely check out the documentation if you would like to dig even deeper, as a lot can be accomplished by knowing as much as possible about the global Window object of JavaScript.