Monday, July 6, 2009

Open a link in a new window, Part 1

Generally, it's best to let users decide if they want to open a link in a new browser window or tab. For some tasks, such as viewing selected items in a library's new books list or a product catalog, it's more convenient for the user to open a single reusable window than to go back and forth repeatedly. There are two basic methods for opening a new window, depending on the doctype of your web page:
  1. Add the target="_blank" attribute to a link
  2. Access the DOM window object with window.open()

Target Practice

The target attribute may still be used with HTML documents that do not specify a doctype, HTML doctypes, and XHTML Transitional, but is not allowed in XHTML strict. Even with XHTML Transitional, it would be better to let target fade into the West. Usage is simple (line wrapped to fit):
<a href="http://destination.html/" target="_blank">
Link title</a>

Let DOM open the window

Using the DOM lets you control the behavior of the link with optional parameters. To simply open a new window (IE) or tab (Firefox), attach the open() method to the link's onclick event (keep open() parameters on one line, wrapped here to fit):
<a href="http://destination.html"
 onclick="window.open(this.href); return false;">
Link Title</a>
To open a new window that grabs focus (is always on top) and can be reused (because it has a name - 'mywin') to prevent a pile of open windows:
<a href="http://destination.html"
 onclick="var newWin = window.open(this.href,
 'mywin'); newWin.focus();
 return false;">Destination Title</a>
To open a new reusable window and specify its size, position, and amount of browser chrome, add optional parameters (keep parameters on one line, wrapped here to fit space):
<a href="http://destination.html"
 onclick="var newWin = window.open(this.href,
'mywin','right=0,top='40',height='500',
menubar='yes',scrollbars='auto',
resizable='yes'); newWin.focus(); 
return false;">Destination Title</a>
For more info on all the available parameters, see the w3chools.com article on HTML open() The last example is getting long and complex, so if you have a list of links that should remain visible while the user selects and views item information, it would be preferable to move the repetitive window.open() specifications to a separate javascript in the <head> of the document or to an external script file. I'll post an example in Part 2 of this topic.

0 comments:

Post a Comment