Just as you can create windows , you should know how to get rid of windows by closing them. In Script 6.10 , the parent window has " open " and "close" links that create and close the child window, and each link has a unique id that we use in the script. The external JavaScript is in Script 6.11 .
1. | This line initializes the value for the newWindow object that we're going to use later. While most browsers do this automatically, some don't, so it needs to be set here to avoid errors later. |
2. | document.links[i].onclick = chgWindowState; In the newWinLinks() function, we're stepping through the links in the document as usual. The only difference here is that we'll call chgWindowState() if we detect a click on one of the links. |
2. | function windowOpen() { if (newWindow && !newWindow. closed) { return true; } return false; } The if statement poses a logical test using the && operator, which returns a true result only if the values on both sides of it are true. So in this case, newWindow must exist and newWindow must not have been closed (the ! is the logical "not" operator). This function returns TRue if a window is open and false if it isn't. |
| |
4. | function chgWindowState() { if (this.id == "closeWin") { Here, we're checking to see if the id of the clicked link is closeWin . If it's closeWin , the user clicked the close link. If it's openWin , they clicked the open link. |
5. | if (windowOpen()) { newWindow.close(); } If the user clicked close and the window is open, these lines close it. |
6. | else { alert("The window isn't open"); } If the user clicked close and the window's already closed, an alert pops up saying so. |
7. | if (this.id == "openWin") { if (windowOpen()) { alert("The window is already open!"); } Similarly, if the user clicked open and the window is already open, an alert pops up saying so. |
| |
8. | else { newWindow = window.open("", "newWin","toolbar,location=yes, width=300,height=200"); } If the user clicked open and there's no current window, the window opens up, showing the parameters set in the line ( Figure 6.11 ). In this case, the toolbar and location are visible. |
9. | We end with a return false so that the HRef doesn't get triggered. |