Automatically Download PDFs via jQuery

Have you ever wanted to have a link to a resource, such as a PDF file, and have that resource be automatically downloaded when the link is clicked? All you need to do is add a download attribute to your link HTML.

<a href="/resources/newsletter.pdf" download>Newsletter</a>

But wait, the download attribute isn’t supported across all the current browsers! It won’t work in Internet Explorer or Safari. So, the next best thing is to make sure that the link opens in a new tab when it can’t be downloaded.

<a href="/resources/newsletter.pdf" target="_blank" download>Newsletter</a>

Since you probably can’t count on your content editors to know HTML, much less reliably set these attributes on every link they create, the best thing would be to add this jQuery code snippet to your site:

Now you have a simple, reliable way to handle download links on your site. If you need to force download other file types, just add some code for the file extensions of your choice.

Comments

  1. Hi, Thanks for the code!
    Now it’s easy to make ‘downloadable’ files.
    I tested the download in Chrome and works seamlessly with .pdf, .jpg and .png. But in Firefox (47.0.1) does not work.
    Can you help with this?

  2. This jQuery applies the “download” attribute each time it encounters PDF files, which makes it so people don’t have to manually put it in. Unfortunately, this attribute is not supported on IE, Edge or Safari. Darn it!!! It’s so hard to get these browsers to support nifty features like this. I’m looking for some code that will force IE, Edge and Safari to download PDFs on a site that I work on because it has fillable forms. Firefox, IE, Edge and the Mac version of Safari do not support fillable forms. So, I’m trying to make it so that all the browsers simply download the PDF files, so people can fill them out offline. It will save a lot of site visitor confusion and overly technical explanations from me.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.