Previous Page
Next Page

Loading Different Contents into a Window

In the previous task, clicking a link created a new window, filled with an image. But what if you have several links on a page, and you want them all to target the same new window? Script 6.3 demonstrates this technique. The main window in Figure 6.4 has three links. Clicking any of the links opens a new window, filled with the image of the appropriate book. If you switch back to the main window and click another link, the image in the smaller window is replaced.

Script 6.3. With this script, you can open a new window and fill it with a variety of content, triggered by clicking different links.

window.onload = newWinLinks;

function newWinLinks() {
     for (var i=0; i<document.links.length; i++) {
        if (document.links[i].className == "newWin") {
            document.links[i].onclick = newWindow;
        }
     }
}

function newWindow() {
     var bookWindow = window.open(this.href, "bookWin","width=135,height=165");
     bookWindow.focus();
     return false;
}

Figure 6.4. Clicking any of the three links opens the smaller window and fills it with the cover image of the appropriate book.


To load different contents into a window:

1.
document.links[i].onclick = newWindow;



In the newWinLinks() function, we've added the newWindow() function call as the onclick handler via JavaScript. When newWindow() is called, it uses this.hrefthat is, the href attribute value from HTML.

2.
function newWindow() {



Here, we're defining a new function called newWindow().

3.
var bookWindow = window.open(this. href,"bookWin","width=135, height=165");



Here in the variable bookWindow, we're opening a new window object, followed by the window's parameters. First, we pass it the value of this.href. The name of the new window is bookWin, and the width and height parameters set the size of the window.

4.
bookWindow.focus();



This line uses the focus() method to tell the window we just opened to come to the front. You can use focus() whenever you need to make a window visible; if there are several windows open, using focus() brings the window to the top.

5.
return false;



The function needs to end with return false so that the HTML knows to not also load the href in.

Tip

  • The opposite of the focus() method used in step 4 is blur(). Using blur() pushes a window behind any other windows that are open. The focus() and blur() methods of the window object have associated onfocus and onblur event handlers, which let you take action when a window gains or loses focus.



Previous Page
Next Page