The Window Object in JavaScript

Table of content:

Introduction to the window object

The window object is created for each window that appears on the screen. The window object differs from the document object in that the window object contains the document object. The window object enables you to add more interactivity to your script.

Properties of the window object

Below is a list of the properties of the window object.

Property Description
closed Holds the value based on whether or not a window has been closed.
defaultStatus Defines the default message displayed in the status bar.
document A reference to the document object of the window.
frames An array that represents all of the frames in a givem window.
history Provides information on the browser history of the current window.
innerHeight Returns the height in pixels of the viewable area within the window.
innerWidth Returns the width in pixels of the viewable area within the window.
lenght Holds a value equal to the number of frames in the window.
location Holds the value of the current URL of the window.
name Enables a window to be named.
opener Refers to the window that opened another window.
outerHeight Returns the width in pixels of the entire browser window.
outerWidth Returns the width in pixels of the entire browser window.
parent Refers to the frame set that contains the current frame.
screen.availWidth Returns the available width of the browser window in pixels.
screen.availHeight Returns the available height of the browser window in pixels.
screen.colorDepth Returns the color depth of the screen in bits per pixel.
screen.height Returns the total height of the screen in pixels.
screen.pixelDepth Returns the bit depth of the screen in bits per pixel.
screen.width Returns the total width of the screen in pixels.
self Provides another way to reference the current window.
status Enables a message to be placed in the status bar; overrides defaultStatus.
top A reference to the top window containing a frame, frame set or nested frame set.
window A reference to the current window.

The closed property

The closed property is used to check whether or not a window has been closed by the viewer. It is normally used with the name of a window followed by the closed property.


if (windowname.closed) {
JavaScript code here
}

Of course, windowname will be replaced by the name of the window you wish to check.

The defaultStatus property

The defaultStatus property sets the text string that is displayed by default in the status bar when nothing has been assigned to the window.status property.

Note:
Most browsers do not display status bar text altered by JavaScript unless the user alters the browser settings. Since it is a security risk to change the browser settings, using defaultStatus property in your script is not recommended.

The frames property (Array)

The frame property is an array that holds a value for each frame within a frame set. This property is often use to find the number of frames in a window and then perform tasks on the frames in sequence.

The innerHeight and innerWidth properties

The innerHeight and innerWidth hold values for the width and height of the area of the window in view. These values do not include scroll bars, menu bars and other browser features.


var myWinWidth = window.innerWidth;
var divWidth = (myWinWidth >= 800) ? "750px" : "400px"

document.write('<div style="width: '+divWidth+'; background-color: #CCC;">');
document.write('This is the text for the new div element');
document.write('</div>');

On the first line the value of innerWidth property is assigned to a variable called myWinWidth.

On the second line the if/else statement determines if the viewer has at least 800px of viewable width or not. If yes then the div element will be 750px otherwise the it will be 400px.

The next three lines are document.write() methods. They just write the HTML part.

The length property

The length property tells you how many frames are there in a window. It is just a shorter version of window.frames.length property, which is more convenient when writing code.

The location property

The location property holds the current URL of the window. This property is often use to redirect viewers to a new URL if the page has been moved.


<html>
<head>

<title>Page 1</title>

<script type="text/javascript" >
window.location = "page_2.html";
</script>

</head>

<body>

No JavaScript enabled?<br>
Click the link below for the new page.<br>
<a href="page_2.html">New Page</a>

</body>
</html>

The JavaScript in the head section sends the viewers to the page_2.html instantly. In the body section there is a link to page_2.html for those who don’t have JavaScript enabled in their browsers.

The name property

As the name suggests, the name property holds the name of the current window and also enables you to give a window a name.

Let’s assign a name to a window then write it into the body of the page.


window.name = "The_No_1_Window";
document.write("The name of this window is "+window.name+" which is a great name!");

The opener property

The opener property is used to reference the window that opened the current window. This property is often used in new windows opened with the open() method. This is helpful if you want to detect if the main window has been closed or not, using the closed property, and if you want to perform an action in the main window through the new one.


if (window.opener.closed)

In the above code, the closed property is added after the opener property in order to check whether the window that opened the current window has been closed.

The parent property

The parent property is used only when there are frames on the page. It allows you to access the parent frame set of the current frame. It can be useful if you want to work on one frame from another frame.

The self property

The self property is another way of saying “the current window” in JavaScript. It is used like the window object and can be useful if you have a lot of windows with names and want to be sure you are using a property of the current window not one of another named window.

The status property

The status property contains the value of the text set in the status bar of the window. Changing this property overrides the content of the status bar with the defaultStatus property.

Note:
You have to be aware that most browsers DO NOT display (by default) status bar text altered by JavaScript.

The top property

The top property is used to access the top window out of all the frame sets.

Note:
To not be confused with parent property which goes to the top of the frame set that contains the current frame. The top property goes to the top window, even if the window contains nested frame sets.

Methods of the window object

The table below lists the most commonly used methods of the window object with a short description for each method.

Method Property
alert() Pops up an alert to the viewer who must then click OK to proceed.
back() Takes the window back one item in the history list.
blur() Removes the focus from a window.
clearInterval() Cancels the action of a setTimeout() method call.
clearTimeout() Cancels the action of a setTimeout() method call.
close() Closes a browser window.
confirm() Displays a confirmation dialog box to the viewer who must then click OK or Cancel to proceed.
escape() Converts special characters in a string of hexadecimal characters.
find() Enables the viewer to launch the Find utility in the browser to find text on a page.
focus() Gives the focus to a window.
forward() Takes the window one item forward in the history list.
home() Sends the viewer to the home page the viewer has set in the browser settings.
moveBy() Moves a window by certain pixel values that are sent as parameters.
moveTo() Moves the top-left corner of the window to the coordinates set as parameters.
open() Opens a new browser window.
print() Prints the content of the window.
prompt() Pops up a prompt dialog box asking the viewer to input information.
resizeBy() Resizes a window by moving the bottom-right corner by certain pixel values that are sent as parameters.
resizeTo() Resize an entire window to the height and width that are sent as parameters.
scrollBy() Scrolls the viewing area of a window by certain pixel values that are sent as parameters.
scrollTo() Scrolls the viewing area of the window to the specified coordinates that are sent as parameters.
setInterval() Calls a function each time a certain amount of time passes.
setTimeout() Calls a function once certain amount of time has passed.
stop() Stops a window from loading its content.
unescape() Converts an escaped string back to its normal characters.

The alert() method

The alert() method pops up a message to the viewer and the viewer has to click OK to continue.


window.alert("Hi and welcome!");

It can be shortened as the following:


alert("Hi and welcome!");

This kind of shortcut will work for almost all the window properties and methods. However, you shouldn’t use this shortcut with new windows and location property.

The confirm() method

The confirm() method gives the viewer a chance to confirm or cancel an action. It returns a Boolean value of true or false and its result is usually assigned to a variable.


var ItIsSure = window.confirm("Are you sure?");

Let’s say that you have a link to another page on your page and you want the viewer to confirm before leaving the page.


<body>

<a href="http://javascript.saigon.ro" id="JS_link">Go to JavaScript.Saigon.RO</a>

<script type="text/javascript" >
var theLink = document.getElementById("JS_link");
theLink.onclick = function () {
var ItIsSure = window.confirm("Are you sure you want to follow the link?");
if (!ItIsSure) {
window.alert("OK, stay here! You are safe with me!");
return false;
}
}
</script>

</body>

If the viewer clicks OK then the function returns true and the viewer is thaken to the link. If Cancel is clicked the function returns false, the link won’t be followed, and an alert is sent to the viewer.

The find() method

The find() method let the viewer find a certain bit of text on your page using the browser’s built-in Find utility.


<form>
<input type="button" value="Find Text" onclick="window.find();" />
</form>

The home() method

The home() method is used to send the viewer to the homepage the viewer has set in the browser settings.


<form>
<input type="button" value="Go to your Homepage!" onclick="window.home();" />
</form>

Note:
This method doesn’t work in all browsers.

The print() method

Using the print() method the viewer can print the current web page. When this method is called, it opens the Print dialogue box so the viewer can adjust the printer settings and print the page.


<form>
<input type="button" value="Print the page" onclick="window.print();" />
</form>

The prompt() method

The prompt() method is used to prompt viewer to enter information. You can use the information the viewer enters in the prompt dialog box to do different things since the information the viewer enters is assigned to a variable.


var YourName = window.prompt("Your text" , "Default entry");

For example, you can use this method to get the viewer’s name and send an alert while the page is loading.


<body>

<div id="greeting">
<h1>Hello and welcome to my page!</h1>
</div>

<div id="content_page">
This page is about JavaScript.
</div>

<script type="text/javascript" >
var greetMe = document.getElementById("greeting");
var YourName = window.prompt("What is your name?" , "");

if (YourName.length < 1) {
YourName = "Anonymous";
}

greetMe.innerHTML = "<h1>Hello "+YourName+"! Welcome to my page!</h1>"
</script>

</body>

The open() method

The open() method allows you to open a new window with javaScript.


window.open("URL" , "name" , "attribute1 = value,attribute2 = value");

The “URL” parameter is replaced with the actual URL of the HTML document that is to be opened in the new window.
The “name” parameter is replaced with the name you give to the new window.
The third parameter is used to add attributes to the new window. These attributes are set by using “yes”, “no”, or a numeric value on the right side of the equal sign.
There is a comma between each attribute and no space!


window.open("mypage.html" , "MyPage" , "width=400,height=300");

Standard attributes

The table below lists the standard attributes you can use as part of the last parameter in the open() method.

Attribute name Possible values Function
width number The width of the new window in pixels.
height number The height of the new window in pixels.
directories yes, no, 1, 0 Defines whether or not the new window has directory buttons (for example: What’s New or
Link buttons near the top of the browser).
location yes, no, 1, 0 Defines whether or not the new window has a location box to type in a new URL.
mmenubar yes, no, 1, 0 Defines whether or not the new window has a menu bar (File, Edit etc).
resizable yes, no, 1, 0 Defines whether or not the viewer is allowed to resize the new window.
scrollbars yes, no, 1, 0 Defines whether or not the new window has scroll bars.
status yes, no, 1, 0 Defines whether or not the new window has a status bar at the bottom.
toolbar yes, no, 1, 0 Defines whether or not the new window has a toolbar (Back and Forward buttons, Stop button etc).

Note:
You can use 1 instead of yes and 0 instead of no.

The following code opens a new window with all the features listed in the table above.


window.open
("newpage.html","Amazing Page","width=300,height=300,directories=1,location=1,menubar=yes,resizable=1,scrollbars=yes,status=yes");

Of course, you have to create the newpage.html and place it in the same directory as the page containing the above script is.

Here is another example that opens the same newpage.html but this time when the viewer clicks a button.


<body>

<p>Click the link below to open a new page!</p>
<a href="newpage.html" id="new_window" >New Page</a>

<script type="text/javascript" >
var NewWindow = document.getElementById("new_window");
NewWindow.onclick = function () {
window.open("newpage.html","Amazing Page","width=600,height=400,status=yes");
return false;

}
</script>

</body>

Extended attributes

The extended attributes are listed in the table below. Note that they might not work in all browsers.

Attribute Possible Values Fuunction
fullscreen yes, no, 1, 0 Defines whether or not the window should open in a full screen.
left number The distance from the left of the screen.
personalbar yes, no, 1, 0 Defines whether or not the new window has a personal toolbar.
screenX number The distance from the left of the screen.
screenY number The distance from the top of the screen.
top number The distance from the top of the screen.

The close() method

The close() method is used to close a window. However, you can close only windows opened by you with JavaScript.

Let’s modify the newpage.html and add a button at the bottom so the viewer can close the window.


<body>
<h1>I am an amazing new window<br>
I have been opened with JavaScript.</h1>
<form>
<input type="button" value="Close Window" onclick="window.close();" />
</form>
</body>

The moveBy() method

The moveBy() method can be used to move a window on the scree from one location to another.


window.moveBy(x-pixels,y-pixels);

A negative number will move the window to the left and to the top, and a positive number will move the window to the right and to the bottom.

Let’s modify the newpage.html again and add a button that can move the window by a number of pixels of your chioce.


<body>
<h1>I am an amazing new window<br>
I have been opened with JavaScript.</h1>
<form>
<input type="button" value="Move Window" onclick="window.moveBy(50,50);" />
<input type="button" value="Close Window" onclick="window.close();" />
</form>
</body>

Since the button is still on the page, you can move the window again and again. It will work as long as it is pressed.

The moveTo() method

The moveTo() method moves the window to a particular location on the screen based on the given coordinates.


window.moveTo(x-value,y-value);

Let’s take the previous example and replace moveBy() with moveTo().


<body>
<h1>I am an amazing new window<br>
I have been opened with JavaScript.</h1>
<form>
<input type="button" value="Move Window" onclick="window.moveTo(50,50);" />
<input type="button" value="Close Window" onclick="window.close();" />
</form>
</body>

The resizeBy() method

The resizeBy() method is used to resize a window. To make it larger use positive numbers and to make it smaller use negative numbers.

The resizeTo() method

The resizeTo() method is used to resize a window to a specific dimension. You have to input the new width and height in pixels in place of the coordinates used in moveTo() method.

The scrollBy() method

The scrollBy() method is used to scroll a window by the number of pixels given in the parameters sent in the method call.

The scrollTo() method

The scrollTo() method is used to scroll a window to a specific destination in pixels based on the parameters sent in the method call.

The setInterval() method

The setInterval() method is used to execute a JavaScript function repeatedly at a set interval.


window.setInterval("function()",time);

If you want to pop up an alert every 5 seconds then you can use the following code:


<body>

<p>An alert will pop up every 5 seconds</p>

<script type="text/javascript" >
function AnnoyingOrange() {
window.alert("I am an annoying orange!");
}
window.setInterval("AnnoyingOrange()",5000);
</script>

</body>

In this case the function is called inside quotes. This prevents the function from executing immediately rather than at the set interval. The function name is sent as a string parameter to the setInterval() method where it is then called at the correct time lapse.

The clearInterval() method

The clearInterval() method is used to end the annoying alerts from the previous code.


window.clearInterval(name);

Before working with the clearInterval() method you have to assign your setInterval() call to a variable.


<script type="text/javascript" >
function AnnoyingOrange() {
window.alert("I am an annoying orange!");
}
var CrazyAlerts = window.setInterval("AnnoyingOrange()",5000);
</script>

Now we can you clearInterval() method by calling it with the CrazyAlerts as a parameter. We can place a button which the viewer can press to stop interval from running.


<body>

<p>An alert will pop up every 5 seconds</p>

<script type="text/javascript" >
function AnnoyingOrange() {
window.alert("I am an annoying orange!");
}
var CrazyAlerts = window.setInterval("AnnoyingOrange()",5000);
</script>

<p>You can click the button below<br> to stop the alerts from popping up.</p>

<form>
<input type="button" value="Stop the alerts"
onclick="window.clearInterval(CrazyAlerts);" />
</form>

</body>

Of course, these alerts are quite useless but the setInterval() and clearInterval() methods are usually used for things that have to be updated regularly (clocks for example).

The setTimeout() method

The setTimeout() method is used to execute a JavaScript function after a certain amount of time has passed. Unlike setInterval() method, the setTimeout() method is executed only once.


<script type="text/javascript" >
function AnnoyingOrange() {
window.alert("Sign Up to continue!");
}
var GuestMode = window.setTimeout("AnnoyingOrange()",5000);
</script>

This code sends the viewer an alert after 5 seconds to sign up in order to continue.
The method is set to the variable GuestMode so we can use it later.

The clearTimeout() method

The clearTimeout() method is used to cancel a setTimeout() call if you call the clearTimeout() before the time expires from the setTimeout() call.


<body>

<script type="text/javascript" >
function AnnoyingOrange() {
window.alert("Sign Up to continue!");
}
var GuestMode = window.setTimeout("AnnoyingOrange()",5000);
</script>

<p>If you click the button below within 5 seconds <br>
the Annoying Orange won't disturb you!</p>

<form>
<input type="button" value="Stop the Annoying Orange"
onclick="window.clearTimeout(GuestMode);" />
</form>

</body>

The code adds a button that if it is clicked on time it cancels the setTimeout() call so the alert won’t pop up.

Leave a Reply