At work today, we were asked by a client to add a link to download Adobe Acrobat onto every page that had a PDF linked on it. Since the site was mostly static, with some content coming from the content management system, we were not interested in adding it to all of the static pages and changing the programming of the CMS output pages.

My co-worker and I decided that the best way to do it would be with JavaScript. Since the site was already using jQuery, our company’s library of choice, it turned out to be quite a simple task. If you just want to get to the code, take a look at the demo.

The Idea

  1. We add the link to download Adobe Acrobat to the site’s template
  2. We hide the link using CSS
  3. We use jQuery to see if there are any links on the page linking to a PDF
  4. If there are, we use jQuery to show the link

The Execution

Ok, simple enough, just add the link to the source of the document:

<p id="acrobatDownload"><a href="http://www.adobe.com/products/acrobat/readstep2.html">Download Adobe Acrobat to view the PDFs on this page</a></p> 

Then, hide it with CSS:

#acrobatDownload { display: none; } 

The jQuery

First, we want to check and see if any of the links on the page end with .pdf. Then, if there are any, we fade in the link:

$(document).ready(function() {
 if($('a[href$=.pdf]').length > 0) {
  $('#acrobatDownload').fadeIn('slow');
 }
}); 

I have created a demo page with a PDF link on it to see this in action.

Conclusion

I can’t even imagine how much time and hassle we saved ourselves by doing this with JavaScript. Plus, it could provide useful to someone who doesn’t have Acrobat (although I can’t imagine that there are many).

The concept is actually quite simple, and my mind is grinding away trying to think of other ways to use jQuery to do things like this.

Can you all think of anything?