How can JavaScript automatically load a new document?
The window object has a property called "location" which can be used to obtain the current document's URL or to specify the URL of a new document to be loaded.window.location can be read from or assigned to. When window.location is read, the result is a string containing the full URL of the current document. For example, the statement
loc = window . location;
when executed within this document, sets the variable loc equal to
On the other hand, when window.location is set by assignment, the document whose URL matches the new value is automatically loaded. For example, the statement
window . location = "http://sharkysoft.com/";
,
if executed, would cause the browser window to be updated with Sharkysoft's home page.
The example just shown demonstrates how full, absolute URLs can be assigned to the window.location object. It is also acceptable to assign partial URL strings to window.location, in which case the new string is treated as a relative URL.
For example, if the current document's URL is
http://www.mysite.com/funstuff/index.html ,then the abbreviated assignment statement
window . location = "intro.html";
is equivalent to full assignment statement
window . location = "http://www.mysite.com/funstuff/intro.html";
because the JavaScript interpreter automatically inserts the missing portion of the URL into the new string.
To help you become more acquainted with the window.location object, here is a "laboratory form" which you can use to experiment with the effects of reading and writing its value:
Before you head off and start using window.location in your code, please consider some final notes on the subject:
location
is usually equivalent to window . location
. Statements executed within event handlers, however, do not necessarily operate within this same scope. Because of this, it is a good idea to to preface the property "location
" with its parent object "window
" when it is used within event handlers. Failure to do so causes the interpreter to inadvertently treat location as a property of document.
Detailed information on the window.location object can be found in Netscape's JavaScript Guide.
Charlton Rose
30 Jan. 1997