Be the first to write a review
Free - Opening PDFs in a new window with JavaScript
Opening documents such as PDFs in a newwindow should be automated using JavaScript for the following reasons:
- Users will often close the web browser when a PDF is opened, mistakenly believing the document has been opened in Adobe Reader
- The attribute historically used to open a new window, target, has been removed from the HTML 4.01 Strict specification (it's now deprecated)
- Opening a new window is a behaviour and should be moved to the behavioural layer.
Using JavaScript can also be particularly useful when a website is content managed. Rather than having to rely on site editors to remember to open a link to a PDF in a new window the process is handled by a simple JavaScript function.
Check out this fully functioning example to see what we'll create. Check out Advanced Layer Popup if you want to open your PDF in a layer that pops up or Advanced Open Window if you want to create a new window with the press of a button.
Warning users the document opens in a new window
The final task is to ensure users are aware that the link will open in a new window. We need to be as clear as we can with this to minimise confusion.
We're going to do this by firstly amending the title text of the link and secondly inserting an image with
alternate text of "(opens in a new window)". The link title can be set as follows:
links[eleLink].title += "\n(opens in a new window)";
Next we will create an image element and set its src and alt attributes. Finally we'll append the image to the hyperlink using the appendChild method.
var img = document.createElement("img");
img.setAttribute("src", "i/new-win-icon.gif");
img.setAttribute("alt", "(opens in a new window)");
links[eleLink].appendChild(img);
The final function is as follows:
function fNewPDFWindows ()
{
if (!document.getElementsByTagName) return false;
var links = document.getElementsByTagName("a");
for (var eleLink=0; eleLink < links.length; eleLink ++) {
if (links[eleLink].href.indexOf('.pdf') !== -1) {
links[eleLink].onclick =
function() {
window.open(this.href,'resizable,scrollbars');
return false;
}
var img = document.createElement("img");
img.setAttribute("src", "i/new-win-icon.gif");
img.setAttribute("alt", "(opens in a new window)");
links[eleLink].appendChild(img);
}
}
}
Conclusion
This very short function demonstrates how easy it is to open links in new windows automatically. This means your site will be more likely to validate, more likely to work correctly in future browsers and will be more usable for its users. Check out this fully functioning example.
This article was written by Paul McCarthy. Paul's crazy about CSS and using JavaScript for good (not evil) - so crazy that he works for Webcredible helping to make the Internet a better place for everyone. He can often be found carrying out an accessibility audit and spends much of his time working on the world's most accessible CMS.