I’ve long been a proponent of opening new windows whenever users clicked on an external link. I figured that, despite the usability concerns, the fact that my site stayed open in a window on their machine made it all worthwhile. Then I read Roger Johansson on the subject. And Jakob Nielsen. And Neil Turner. Needless to say I’ve come around, and won’t be opening external links in new windows anymore. However, there are still some cases (namely PDFs) where you can still benefit from opening a new window, and since the target attribute breaks strict validation, how can we apply the same functionality to our sites using a different method?

Opening New Windows for PDF Links

For usability purposes, we’ll want PDF links to open in a new window, and be styled differently so the user can anticipate the alternative behavior. Any solution to alter these links should be unobtrusive, efficient, and standards-compliant. We could specify a class of “pdf” on the a tag every time we published a link to a .pdf file, but with the aid of Robert Nyman’s DOMAssistant, we won’t have to. Here’s the code:


// Handles dynamic changes to site links
var linkHandler = linkHandler ? linkHandler : {
	// Call the link initialization functions
	init: function() {
		linkHandler.setPDFs();
	},
	// Sets the class of pdf links to pdf and adds the newWindow handler
	setPDFs: function() {
		$("a[href$=.pdf]").each(function() {
			$(this).addClass("pdf");
			$(this).addEvent("click",function() {
				linkHandler.newWindow(this.href);
				return false;
			});
		});
	},
	// Creates the new window and brings it to the front of the screen
	newWindow: function(url) {
		var newW = window.open(url, 'NewWindow', 'width=760,height=550,scrollbars=yes,resizable=yes,menubar=yes,toolbar=yes,location=yes');
		if (typeof newW == 'object') { newW.focus(); }
	}
};

And there you have it! With this script, the following code:


<a href="/lib/pdfs/test.pdf">Test PDF</a>

Will produce the following result:

Test PDF

About

Not Just a Hat Rack (NJHR) focuses on best practice solutions for problems you’ll encounter during a typical site build. There’s an emphasis on new technology when possible (HTML5, CSS3, etc.), but all suggested solutions will work cross-browser, quickly and efficiently. more »

I'm Andrew Church, an aspiring web developer currently living and working in Washington, DC. I’ve been employed as a professional developer since 2004, when I graduated with a degree in Information Sciences & Technology from Penn State University. I'm particularly interested in front-end web development technologies (HTML, CSS, JavaScript), but I do have experience with the entire site build process. « less

Tweets

Delicious