Object window. Manipulating browser windows from JavaScript.

We already mentioned object window, but so far we treated this object as a container for other elements (document or location). However, this object by itself has a lot of inresting properties and even more interesing methods. We'll start this lecture with discussing some of these methods.

Methods of object Window

Cretaion new windows

There are several methods of this object that allows users to create new windows. Here they are: Method alert() is the simplest of these method. It takes one atring argument and creates a small message window that contains this string as a message and an "OK" button, which closes the window. Here is an example of code that illustates usage of the method:
window.alert('Hello! This is my message to you!');
We can also use this method as an event handler:
Code Result
<form>
 <input type=button value="Alert"
  onClick="alert('This is my second message.\nIt contains two lines.');" >
</form>
   
In the last example please notice two things:

Method confirm() allows us to ask user a true/false question. This method takes one string argument and creates a window with this message and two buttons OK and Cancel. This method returns true if user clicked OK button and false otherwise. Here is an example:
Code Result
function submitting()
{
  var msg = "You left some fields of the form empty. "+
            "Are you sure you want to submit the application?";
  if( confirm(msg) )
    alert('You want to submit!');
  else
    alert("Let's get back to the form then");
}

...
<input type=submit onClick="submitting();">

Method prompt() is the next step in asking user questions. This methods allows to ask a question and get a string as an answer. This method takes two arguments:

  • the first argument is a prompt string (this is a required argument). This string will be displayed in the prompt window
  • the socond argument is optional. This argument may contain a string, which sets the default value of the user's input. This method generates a window that contains a prompt string, a text input element, and two buttons OK and Cancel. If Cancel button was clicked, then this method returns null. If OK button was pressed, this method returns either the string entered by the user or the default string (if user didn't type anything). The following example shows how to use this method:
    Code Result
    function get_name()
    {
      var name;
      name = prompt('Please enter your name', '');
      if( name )
        alert('You entered "'+name+'"');
      else
        alert('You did not type any name or pressed Cancel to close the window');
    }
    ...
    <form>
     <input type=button value="Ask my name" onClick="get_name();">
    </form>
    

    Method open() opens a new browser window. This method can take up to four arguments, however, none of them is required. These arguments are:

    1. url. The first argument may contain the address of the page you want to download into the new window.
    2. name. The second argument sets the name of the new window. This name can be used as a target parameter of several HTML tags (such as form or a). This parameter allows to download another document in already opened window. It's important to understand that you can not provide the second argument withouth specifying the url first. If you try do do this, then the argument you provided will be treated by JavaScript as the url not name.
    3. features. The third argument is a string with properties of the window you are creating. These properties can control such things as size of the window, scroll bars, menu, etc. We'll discuss these properties later.
    4. replace. This argument is a boolean value that defines how the new address should be trreated in the window history.

    Window elements

    Element Value Description
    height pixels Sets the initial height of the new window.
    width pixels Sets the initial width of the new window.
    top pixels Sets the Y-coordinate of the top-left angle of the new window.
    left pixels Sets the X-coordinate of the top-left angle of the new window.
    directories yes|no or 1|0 Display or hide the directories in the new window.
    location yes|no or 1|0 Display or hide the location bar in the new window.
    menubar yes|no or 1|0 Display or hide the menu in the new window.
    resizable yes|no or 1|0 Allow the user to resize the new window or prohibit resizing.
    scrollbars yes|no or 1|0 Display or hide the scroll bar of the new window.
    status yes|no or 1|0 Display or hide the status bar in the new window.
    The features argument is a string in the form
    "feature1=value1; feature2=value2; ..."
    
    Example:
    window.open('mypage.html', 'win1',, "status=no; menubar=no; scrollbars=yes");
    
    The following example allows you to open windows with different parameters.

    Manipulating with window

    Mathod window.open() returns a reference to the newly created window. Using this reference (which is, in fact, just another object of the type Window) we can manipulate this new window. To do this we can use other methods of the object Window: Let's look at them one by one.

    The easiest and probably the most useful is method close() that closes the window which calls is. Here is a small example where in the first line we open another window and memorize the reference to the new window in variable new_win. In the second line we close the window by using method close() called as method of new_win object:


    Method moveTo() takes two integer arguments top and left and moves the window in such a way that the top left corner of the window is located at the point with coordinates top and left. The following example moves the window created in the previous example in the position with coordinates 100 and 200:

    Similarly method moveBy() takes two integer arguments shift_right and shift_bottom and moves the window by the given shifts from its current position. This method can also take negative arguments to move the window up and/or left:

    Methods resizeTo() and resizeBy() allow us to change the size of the window. The first of these methods sets a new window sizes, which are specified as arguments:

    The other method changes the current size of the window by the arguments specified:

    Two more methods scrollTo() and scrollBy() allow us to scroll the window.
    Notice: if you want to change size, scroll, move, or close the current window you should use methods of this window; that is, window.close() or window.resizeTo(100,100). If you want to apply these methods to another window you need to use the variable where you stored the refernce to that window (for example, win1) and use methods of these object: win1.close() etc.

    More window control and information

    When we work with several windows from JavaScript we should always be careful about closed windows. As you can easily guess all the methods above can be applied only to open windows. When we are closing a window from a script it is always a good idea to assign special value null to this window reference. Unfortunately, user may decide to close this window manually. Can we get to know if a particular window open or closed. Fortunately, we can. Each window has a special property closed wich contains a boolean value indicating this. If a window is open this property is set to false when the window is closed this property is set to true. Thus, before performing any operation it is very useful to do some checking like we do below:

    One more useful method of the Window object is method focus(). This method brings the window called the method up front. This can be used when you work with several windows and want to show a window hidden behind the others:

    Using JavaScript we can control the current window and any child window we created in this script. An interesting question is whether a child window can control the parent window. The answer is yes. However, to do so the child window needs to have a reference to the window, which opened this child. This reference is to be kept in property opener of the Window object. A web page designer should take care about assigning a proper value to that property manually, though. Usual procedure of opening a new window looks like shown in the example below:

    var child_win = null;
    child_win = window.open(url, name, features);
    if( child_win != null ){
      new_win.opener = window;
      ...
    }
    else{ // an error happened. Browser couldn't open a new window
      alert('Error: cannot open a new window.');
      ...
    }
    
    This example shows how two windows parent and child can control each other.

    Creating window content on-fly.

    Sometimes we do not have a page to load into a new window and moreover the new window content should be generated based on user's input. How can we do that? How can we specify the content of a window? To answer these questions we need to talk about three methods of the document object. These methods are: The first two methods write() and writeln() both take a string as an argument and add the string to the document that runs the method. For example,
    /* add the header to the current document */
    document.write('<h2>This header is generated by JavaScript</h2>');
    // add an image to the child window 
    child_win.document.writeln('<img src="../images/excl.gif">');
    
    The only difference between these two methods is that method writeln() adds a new line symbol '\n' at the end of the line.

    Method close() (do not be confused with method close() of Window object) closes the document for input; that is, no more lines can be added to it. This method is useful in a situations like the one described below. Assume we need to open a window named my_new_win and add several lines to it:

    If you click on the text of the example, the code shown will be executed and you'll see a new window created with two headers in it. Now let's click there one more time. What's going to happen? Since a window with name my_new_win already exists the browser will not recreate it. Since method close() hasn't been deployed to the document in the new window we are still allowed to add lines there. Thus, the same two headers will be added to the window. Now let us try the same code with the calling method close() at the very end.
    Now the second execution of the same code rewrites the content of the document in the window.