Download a file via jquery and redirect

20,645

Let's say you have a link to your download page

<a class="downloadLink" href="www.example.com/foo.pdf">Download</a>

In your Javascript:

$(".downloadLink").click(
    function(e) {   
        e.preventDefault();

        //open download link in new page
        window.open( $(this).attr("href") );

        //redirect current page to success page
        window.location="www.example.com/success.html";
        window.focus();
    }
);
Share:
20,645
Matt Lambert
Author by

Matt Lambert

Designer &amp; Developer at mattlambert.ca, Head of Design at Stellar Labs

Updated on August 01, 2020

Comments

  • Matt Lambert
    Matt Lambert almost 4 years

    I'd like to figure out a simple way using jQuery to trigger a download when a text link is clicked. Also, after click the user is redirected to success page. Can anyone help?

  • Matt Lambert
    Matt Lambert over 12 years
    Thank you! Much appreciated :)
  • Sam
    Sam almost 9 years
    If The download link was a PDF this would mean the redirect would be the primary page and the PDF would become a second tab. Is there a way to reverse this, so they are taken to the PDF with a second tab being the redirect?
  • JuliSmz
    JuliSmz about 3 years
    Seems like this stopped working on the last Chrome version...