Using jQuery to automatically download a PDF file

I’ve been working through one of those client requests that isn’t use too often. They wanted a PDF be automatically downloaded after submitting their email (the only field on the form).

I started thinking about different scenarios, particularly this one:

If a visitor successfully completes the form and hits submit, should the PDF open on a new window tab or should it be automatically be downloaded?

I came up with an awesome solution, two methods that work slightly the same.

Method #1


<script>
jQuery(document).ready(function() {


      if (jQuery("#confirm-download").length) {

        var pdfDocument = jQuery("#download-pdf").attr("href");

        var newTab = window.open(pdfDocument, '_blank');
        newTab.location;
        
      } 
      

});
</script>

The problem with the #1 method is that trigger a browser pop up blocker. I spent hours on this subject and there’s no way around it with javascript/jQuery.

The only workaround would be to reload the PDF document on the same URL, see method #2.

Method #2


<script>
jQuery(document).ready(function() {


      if (jQuery("#confirm-download").length) {

        var pdfDocument = jQuery("#download-pdf").attr("href");

        jQuery.get(pdfDocument, function() {
          window.location.href = jQuery("#download-pdf").attr('href');
        });
        
      } 
      

});
</script>

My particular project didn’t need a submit() or click() handler but if you wanted to integrate that you just need to wrap the function within an event handler of your choice. Yeah, my particular situation a bit unique.

For most situations you’re probably going to run into a more common scenario where the event handler is attached to the button itself. If you’re interested in this approach, I’ve got you covered.

Check it out…


<script>
jQuery(document).ready(function() {
 
      jQuery("#the-button-that-is-clicked").click(function() {

        if (jQuery("#check-input-field").val() != '') {
 
          var pdfDocument = "/wp-content/uploads/the-pdf-file.pdf";
   
          var newTab = window.open(pdfDocument, '_blank');
          newTab.location;

        } else {

          return false; // optional
        
        }
      });
});
</script>

The last final solution you might have thought about would be html5’s download attribute, look I think it’s awesome – at the time of this posting it is only supported by the latest browsers though.

Download Attribute Browser Support

The download attribute in action below:


// (.img, .pdf, .txt, .html, etc.)
<a href="/pdf/pdf-file.pdf" download>Download</a>