Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

568 LESSON 20: Working with Frames and Linked Windows


use the open method of the window object. Here’s a JavaScript function that opens a
window:
function popup(url) {
mywindow = window.open(url, 'name', 'height=200,width=400');
return false;
}

The function accepts the URL for the document to be displayed in the new window as an
argument. It creates a new window using the window.open function and assigns that new
window to a variable named mywindow. (I explain why we assign the new window to a
variable in a bit.)
The three arguments to the function are the URL to be displayed in the window, the name
for the window, and a list of settings for the window. In this case, I indicate that I want
the window to be 400 pixels wide and 200 pixels tall. The name is important because if
other links target a window with the same name, either via the window.open() function
or the target attribute, they’ll appear in that window.
At the end of the function, I return false. That’s necessary so that the event handler used
to call the function is stopped. To illustrate what I mean, it’s necessary to explain how
this function is called. Instead of using the target attribute in the <a> tag, the onclick
handler can be used, as follows:
<a href="whatever.html" target="_blank" onclick="popup('whatever.html')">Pop up
</a>
Of course, it’s preferable to use unobtrusive JavaScript and add an appropriate event han-
dler in a script tag. However, this works for the purposes of an example.
Ordinarily, when a user clicks the link, the browser calls the function and then goes right
back to whatever it was doing before, navigating to the document specified in the href
attribute. Returning false in the popup() function tells the browser not to continue what
it was doing, so the new window is opened by the function, and the browser doesn’t
follow the link. If a user who had JavaScript turned off visited the page, the link to
whatever.html would still open in a new window because I included the target attribute,
too.
In the preceding example, I specified the height and width settings for the new window.
There are several more options available as well, which are listed in Table 20.4.
Free download pdf