Previous Page
Next Page

Opening Multiple Windows

Sometimes you'll want to open multiple windows using a script; for example, you might want to create a script that opens a different window every time the user clicks an on-screen control. As usual, JavaScript is up to the task. In this example, we have a page with three links; clicking a link opens up a separate window containing an image; clicking another link brings up another window, one for each link. Script 6.4 shows you how it's done, and Figure 6.5 shows the result.

Script 6.4. When you need to open multiple windows from multiple links, this script does the trick.

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 winName = this.id + "Win";
     var bookWindow = window.open(this.href, winName,"width=135,height=165");
     bookWindow.focus();
     return false;
}

Figure 6.5. Clicking the three links in the rear window produces a veritable constellation of child windows.


To open multiple windows with a script:

1.
function newWindow() {



Create a function called newWindow.

2.
var winName = this.id + "Win";



The variable winName is based upon the id of the calling link, plus the string Win.

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



This line gives bookWindow its value and uses the window.open method to open the window specified by the parameters inside the parentheses. The key to this script is that winName (the second parameter to window.open) is unique. So long as each window name is different, new windows will open.

Tips

  • Clicking the link for a book whose window is already open causes the window to redraw, rather than having a duplicate window open.

  • If you want a new window to open up each time a user clicks a link (versus refreshing an existing window), add a random number to the window name.



Previous Page
Next Page