Native Javascript Ninjutsu: Window object methods & properties

Ninja kanji

Sensei Says (dark ages, to dojos, to disciplines)

Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable – even malicious – ‘copy and paste’ language. Macromedia’s Shockwave – which later became Macromedia Flash, which even later became Adobe Flash – pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.

And then the frameworks came to rise: Dojo, Yahoo! UI Library, Google Web Toolkit, jQuery, Prototype, MooTools, and many more. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.

Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today’s programmers can write pure native Javascript without the aid of a framework? How many can perform AJAX requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks – and thus risk sliding backwards into the dark ages – we must maintain a wide variety of practices: these are the native Javascript disciplines.

Discipline 8: Sui-ren (water training)

NOTE: This article was written with the JS beginner in mind, so it will likely bore the rest of you!

Last week’s article covered the most useful properties and methods of the document object, so this week I’d like to zoom out a bit and explore the window object. Just like the document object, the window object has a variety of its own properties, objects, and methods, though we’ll only go over the most useful and interesting ones. Here’s a quick list of what we’ll discuss:

Properties/Objects:

Methods:

Let’s take a look at some of the most useful (and cross-browser compatible) properties first:

window.document

We’ve already discussed the document object in the previous article so I won’t go into detail, though it’s important to note that this object is a property of the window object.

window.frames

The window.frames property stores an array of all the frames in the given window. You can access a particular frame by providing it’s index number (remember that the index count of an array begins with 0, not 1):

[js]
var first_frame = window.frames[0];
var second_frame = window.frames[1];
[/js]

Once you’ve referenced a particular frame using the frames property you can access its properties:

[js]
var first_frame = window.frames[0];
var second_frame = window.frames[1];
var first_frame_source = first_frame.location;
var second_frame_source = second_frame.location;
[/js]

You can read more about the frames property in my previous post, DOMinating iframes.

window.length

The window.length property stores the number of frames in the given window. This should return the same result as window.frames.length:

[js]
var number_of_frames = window.length;
[/js]

window.location

The window.location property is actually an object which stores all the data about the given window’s current URL:

[js]
var the_current_url = window.location;
[/js]

The location object also has its own properties for returning various parts of the URL. The location.href property will also return the entire URL:

[js]
var the_current_url = window.location.href;
[/js]

The protocol property will return the protocol being used (such as HTTP, HTTPS, FTP, FTPS, etc):

[js]
var the_current_url_protocol = window.location.protocol;
[/js]

The port property will return the port being used (if one was explicitly provided):

[js]
var the_current_url_port = window.location.port;
[/js]

The host and hostname properties will return the host part of the URL:

[js]
var the_current_url_host = window.location.host;
var the_current_url_host = window.location.hostname;
[/js]

The pathname property will return the full path of the current URL:

[js]
var the_current_url_path = window.location.pathname;
[/js]

The hash property will return the anchor of the current URL (if one is provided):

[js]
var the_current_url_hash = window.location.hash;
[/js]

The search property will return the query parameters of the current URL (if any ar provided):

[js]
var the_current_url_query_parameters = window.location.search;
[/js]

The location object also has some of its own methods, but I hardly ever use them in my native JS missions so I won’t explain them here.

window.name

The window.name property stores the value of the window’s name attribute. You can retrieve and set this value:

[js]
var the_old_name = window.name;
window.name = ‘the new window name’;
[/js]

window.navigator

The window.navigator object can be quite an extensive subject and I find it deserves its own article, so I’ll be discussing the navigator() object in the next post in this series. Stay tuned for that if you’d like some more detailed info about this property.

window.parent

The window.parent property references the parent of the given window:

[js]
var the_parent = window.parent;
[/js]

This can also be used recursively:

[js]
var the_parent = window.parent;
var the_grandparent = window.parent.parent;
[/js]

window.self

The window.self property allows you to reference the current window:

[js]
var the_current_window = window.self;
[/js]

window.top

The window.top property allows you to reference the topmost window:

[js]
var the_topmost_window = window.top;
[/js]

There are many more properties that belong to the window object, though these are the ones that I find most useful in real-world applications. These are also the ones that I’ve found to be fully cross-browser compatible and W3C compliant in my testing and research. Let’s continue our exploration of the window object by looking at a few of it’s most useful methods:

alert()

The alert() method is one of the most useful and commonly applied functions I can think of: it’s used constantly in early production, testing, and debugging stages of any native JS code. It’s fully cross-browser compatible and incredibly easy to use:

[js]
alert( ‘This is the alert message’ );
[/js]

The above code will open an alert box in the browser and display your message within it.

confirm()

Very similar to alert(), the confirm() method will open a confirmation box in the browser that will include your message, an ‘OK’ button and a ‘Cancel’ button. It’s also cross-browser compatible and fairly easy to use:

[js]
confirm( ‘This is the confirmation message’ );
[/js]

The message is optional but it’s wise to include one, otherwise your users won’t know what they are confirming. Now if you want to check for which button the user has pushed you can do the following:

[js]
var user_pushed_ok = confirm( ‘This is the confirmation message’ );
if ( user_pushed_ok == true )
{
// User pushes ‘OK’
}
else
{
// User pushed ‘Cancel’
}
[/js]

prompt()

The prompt() method is similar to both the alert() and the confirm() methods: it opens a browser alert message. The difference is that prompt() prompts the user to input some text. Again, it’s relatively simple to use:

[js]
prompt( ‘This is the prompt message’ );
[/js]

Just like confirm() the first parameter is optional. You can also provide a second parameter to specify if there should be default text filled in for the user:

[js]
prompt( ‘This is the prompt message’, ‘This is the default text’ );
[/js]

In order to use the text inputted by the user you’ll have to save the returned value of the method to a variable (as we do above with the confirm() method):

[js]
var the_user_input = prompt( ‘This is the prompt message’, ‘This is the default text’ );
[/js]

setInterval()

The setInterval() method is used to trigger a piece of code (typically a function call) over and over again until either the window is closed or the clearInterval() method has been called (see below for a description of this method). The method takes three parameters: the code to execute, the interval between executions (in milliseconds), and the script language (optional). For the sake of simplicity in this article we will just focus on the first two parameters:

[js]
function theMethodToRepeat()
{
// Do something
}

setInterval( ‘theMethodToRepeat()’, 5000 );
[/js]

The above code will call theMethodToRepeat() function every five seconds. This will happen forever until the window is closed or the clearInterval() method is called.

clearInterval()

The clearInterval() method can be used to stop the looped execution of a setInterval() method. It’s relatively simple to use and requires you to store the return of the setInterval() method into a variable:

[js]
function theMethodToRepeat()
{
// Do something
}

var the_interval = setInterval( ‘theMethodToRepeat()’, 5000 );

function stopTheInterval()
{
the_interval = clearInterval( the_interval );
}
[/js]

Whenever you wanted the loop to be stopped you could simply make a call to the stopTheInterval() function and it will clear the interval loop.

setTimeout()

The setTimeout() method works almost identical to the setInterval() method except that it does not automatically loop over and over again. Instead, it waits the given amount of time and only executes the given code (typically a call to a function) once:

[js]
function theMethodToCall()
{
// Do something
}

setTimeout( ‘theMethodToCall()’, 5000 );
[/js]

The above code will execute theMethodToCall() function after waiting five seconds. In order to use this in a loop you must include the setTimeout() method inside of the function it calls:

[js]
function theMethodToCall()
{
// Do something

setTimeout( ‘theMethodToCall()’, 5000 );
}

theMethodToCall();
[/js]

As you can see, theMethodToCall() function is executed over and over again, every five seconds. Just like the setInterval() method, the setTimeout() method can be canceled using the clearTimeout method.

clearTimeout()

[js]
var the_timeout;

function theMethodToCall()
{
// Do something

the_timeout = setTimeout( ‘theMethodToCall()’, 5000 );

if ( someValue == true )
{
clearTimeout( the_timeout );
}
}

theMethodToCall();
[/js]

The code above checks if someValue equals true, and if it does then the clearTimout() method is called to make sure the loop is broken.

window.open()

To be honest, I hardly ever use this method in my live production work, though I thought it was still worth describing. The window.open() method can be used to open a new browser window. It has four parameters which are all optional: the URL, the window name, the window specs, and a replace flag. If you use the method with no parameters it will simply open a blank window:

[js]
window.open();
[/js]

Specifying a URL and a window name is extremely straightforward:

[js]
window.open( ‘http://somedomain.com’, ‘The name of the new window’ );
[/js]

Passing in window specs is a bit more complex. You need to pass them as a comma separated list:

[js]
window.open( ‘http://somedomain.com’, ‘The name of the new window’, ‘width=800, height=600′ );
[/js]

There are many specs that you can define, though the most useful are the ones that are fully cross-browser compatible:

  • width (window size, in pixels)
  • height (window size, in pixels)
  • left (window location, in pixels)
  • location (window has an address field, true or false / 0 or 1)
  • menubar (window has a menu bar, true or false / 0 or 1)
  • resizable (window is resizable, true or false / 0 or 1)
  • scrollbars (window has scrollbars, true or false / 0 or 1)
  • status (window has a status bar, true or false / 0 or 1)
  • titlebar (window has a title bar, true or false / 0 or 1)
  • toolbar (window has a tool bar, true or false / 0 or 1)

Lastly, the replace parameter specifies whether the new window will add a new entry in the browser history or replace the current entry. This parameter should be set to true or false.

Now if you want to use JS to open a new window and write specific elements to it’s DOM then you’ll have the store the return of the window.open() method to a variable:

[js]
var the_new_window = window.open();
the_new_window.document.write( ‘<p>This is a paragraph tag in the new window!</p>’ );
the_new_window.focus();
[/js]

This code is pretty self-explanatory and the only part we haven’t gone over is the focus() method which I will describe below. Keep in mind that using the window.open() method is pretty risky because many browser settings will detect this action as a pop-up window and block it from the user.

window.close()

Using the window.close() method to close a window is pretty simple:

[js]
var the_new_window = window.open();
the_new_window.document.write( ‘<p>This is a paragraph tag in the new window!</p>’ );
the_new_window.focus();

function closeTheNewWindow()
{
the_new_window.close();
}
[/js]

As you can see in the code above we call the close() method on the appropriate variable (which stores the window reference) and we can close it quickly and easily.

window.focus()

In one example above I used the focus() method and I thought it would be wise to briefly explain that this method can be used to set which window has the current focus (which one is on top). It’s simple to use:

[js]
some_window.focus();
[/js]

window.blur()

And to compliment the focus() method is the blur() method, which does the exact opposite: removes the focus from the referenced window:

[js]
some_window.blur();
[/js]

There are many more methods and properties that belong to the window object, but I find that the above mentioned ones are the most essential for your native JS knowledge. I hope this short tutorial has been helpful for you beginners out there. Stay tuned for next week’s discipline: Navigator object browser detection.

Previous Disciplines
Discipline 1: AJAX with XHR
Discipline 2: Dynamic JS with PHP
Discipline 3: Include External JS
Discipline 4: Cookies and Variables
Discipline 5: removeNode vs. removeChild
Discipline 6: DOMinating iframes
Discipline 7: Document object methods & properties

Resources
W3Schools’ HTML DOM Window Object

Are you smart? Innovative? Driven? If you’re interested in working on challenging projects in one of the world’s most fast-paced industries, why not check out the openings on our Careers page?

Back to news overview