Click here to Skip to main content
15,868,034 members
Articles / Programming Languages / Javascript
Article

Opening PDFs in a new window with JavaScript

Rate me:
Please Sign up or sign in to vote.
3.69/5 (8 votes)
5 Aug 20074 min read 133.7K   32   10
Learn how to use unobtrusive JavaScript to automatically open all PDFs in a new window.

Introduction

Opening documents such as PDFs in a new window 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.

The JavaScript

So you can see what we're aiming to do, check out this fully functioning example.

Registering an event

The first task is to create an event that occurs when the page has loaded. Rather than trying to execute a function call using <body onload="callfunction()"> within the HTML page we're going to use Simon Willison's addLoadEvent(func). This will allow us to add function calls once the page has loaded.

We'll type the following JavaScript into the .js file (all subsequent code should be entered before this function so the addLoadEvent is last):

JavaScript
function addLoadEvent(func)
{
  var oldonload = window.onload;
  if (typeof window.onload != 'function')
  {
    window.onload = func;
  } else {
    window.onload = function()
    {
      oldonload();
      func();
    }
  }
}
addLoadEvent(fNewPDFWindows); 

The function fNewPDFWindows()

We'll create an empty function in the JavaScript file called fNewPDFWindows. To avoid any JavaScript errors with the script, we also check to see if the command getElementsByTagName is available:

JavaScript
function fNewPDFWindows ()
{
  if (!document.getElementsByTagName) return false;
} 

The second task is to create an HTML object collection of any links within the page. The following line gets all links within the page:

JavaScript
var links = document.getElementsByTagName("a"); 

We insert this line after the check to see if getElementsByTagName object method exists as follows:

JavaScript
function fNewPDFWindows ()
{
  if (!document.getElementsByTagName) return false;
  var links = document.getElementsByTagName("a");
} 

The next task is to loop through all of the links and check to see if we want to open any of the links in a new window. If the link is to a PDF document then we'll open it in a new window.

Looping through the links

First we create the loop that goes through all the links in the page, as follows:

JavaScript
function fNewPDFWindows ()
{
  if (!document.getElementsByTagName) return false;
  var links = document.getElementsByTagName("a");
  for (var eleLink=0; eleLink < links.length; eleLink ++) {
  }
} 

The indexOf method

Next we need to determine as we loop through the links whether the link is to a PDF document or not. The indexOf method is ideal for this by returning the index of the search value (the position of the search value in the string). The indexOf method requires a search value but you can also specify where to start the search from within the string (in this example we don't need to pass the method this parameter):

So pass the indexOf method the string ".pdf" to find out if the file being linked to is a PDF document. The indexOf method returns either -1 if the string isn't found or the index of the matching text.

JavaScript
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) {
    }
  }
} 

onclick function

Next we need to apply an onclick event to each of the links to PDF documents, so when they're clicked the new window is opened:

JavaScript
links[eleLink].onclick =
  function() {
  } 

First, let's open the new window, and give the window some parameters. The parameters we're going to pass are as follows.

  • URL - the document we want to display in the new window
  • Specs - a comma separated list of window properties such as scrollbars etc

For a comprehensive list of windows properties take a look W3C schools DOM open method page.

The completed function in this example is as follows. This opens the link address in a new, re sizable window with scrollbars:

JavaScript
links[eleLink].onclick =
  function() {
    window.open(this.href,'resizable,scrollbars');
    return false;
  } 

We insert the onclick event within the if statement that detects whether a PDF document has been found:

JavaScript
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;
        }
    }
  }
} 

Warning users the document opens in a 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:

JavaScript
links[eleLink].title += "\n(opens in a new window)"; 

Next we will create an image element and set it's src and alt attributes. Finally we'll append the image to the hyperlink using the appendChild method.

JavaScript
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:

JavaScript
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United Kingdom United Kingdom
Trenton Moss is crazy about usability and accessibility - so crazy that he founded Webcredible, an industry leading user experience consultancy, to help make the Internet a better place for everyone. He's very good at information architecture and interaction design.

Comments and Discussions

 
GeneralHate new windows, like notificatin and icon. Pin
JLuterek4-Dec-07 2:24
JLuterek4-Dec-07 2:24 
QuestionWhat's about images with pdf links? Pin
Solo7215-Aug-07 4:02
Solo7215-Aug-07 4:02 
AnswerRe: What's about images with pdf links? Pin
Solo7216-Aug-07 0:02
Solo7216-Aug-07 0:02 
GeneralNot working! Pin
gbauer7-Aug-07 3:59
gbauer7-Aug-07 3:59 
GeneralI could not understand Pin
DeltaSoft6-Aug-07 23:22
DeltaSoft6-Aug-07 23:22 
GeneralRegExp instead of indexOf Pin
jeremyjee6-Aug-07 22:21
jeremyjee6-Aug-07 22:21 
GeneralRe: RegExp instead of indexOf Pin
DeltaSoft6-Aug-07 23:23
DeltaSoft6-Aug-07 23:23 
QuestionThis is progress? Pin
Fred_Smith6-Aug-07 11:53
Fred_Smith6-Aug-07 11:53 
AnswerRe: This is progress? Pin
Paul B.7-Aug-07 7:28
Paul B.7-Aug-07 7:28 
AnswerRe: This is progress? Pin
JLuterek4-Dec-07 2:21
JLuterek4-Dec-07 2:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.