Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Opening PDFs in a New Window with JavaScript

By Paul McCarthy
2008-01-23


The JavaScript

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

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

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()

Create an empty function in your JavaScript file called fNewPDFWindows. To avoid any JavaScript errors with the script, check to see if the command getElementsByTagName is available:

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:

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

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

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 create the loop that goes through all the links in the page, as follows:

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.

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:

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

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

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

  }

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

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:

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.

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);

      }
    }
}



Tutorial Pages:
» Introduction
» The JavaScript
» Conclusion


 | Bookmark
Related Tutorials:
» JavaScript Debugging Techniques with Firebug
» Striped Tables Using JavaScript
» Essential Javascript -- A Javascript Tutorial
» Submit Forms Conditionally using JavaScript
» How to Setup a Randomising Function
» Introduction to JavaScript Tutorial

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources