Steve
Steve

Reputation: 2588

Download File after JQuery processing on a link

I am downloading a file through the link and want to process JS before the link download. Through JS, I am showing modal within which, if a person agrees, the link should have the file downloaded, and if a person disagrees, the file shouldn't download.

Below is how I tried. I want it to stop till the user press Yes/No and then it proceeds to either download or not.

Is there a way to do this through JS?

Link:-

<a class="download-video" href="http://mylink.mp4?file=1&name=A Video" download> Download</a>

This is what I tried from this question:-

$('a.download-video').click(function(event) {

    var href = this.href;
    e.preventDefault();  //stop the browser from following
    window.location.href = href;
});

Upvotes: 0

Views: 919

Answers (3)

mehulmpt
mehulmpt

Reputation: 16567

You can set a data-href property and use it if user agrees:

<a class="download-video" href="#" data-href="http://mylink.mp4?file=1&name=A Video"> Download</a>

$('a.download-video').click(function(event) {
    // logic
    if(allGood) {
       var link = $(this).attr('data-href');
       $('<a href="'+link+'" download style="visibility:none"></a>').appendTo('body').click();
    }
});

Upvotes: 1

APAD1
APAD1

Reputation: 13666

You can do this with a conditional statement. In my example I am using the confirm method, but you could also do this with a custom yes/no design.

What the code does is prompt the user to confirm that they want to download the file, if the user hits "ok" then the file will download, otherwise if they click "cancel" event.preventDefault(); is called which cancels the download.

$('a.download-video').click(function(event) {
    if (!confirm('Download File?')) {
      event.preventDefault();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="download-video" href="https://www.w3schools.com/html/mov_bbb.mp4?file=1&name=A Video" download> Download</a>

Upvotes: 2

Kroneaux Schneider
Kroneaux Schneider

Reputation: 294

You should have a var that might be true if the user press "Yes" and false if user press "No". After that:

$('a.download-video').click(function(event) {
    var href = this.href;
    e.preventDefault();  //stop the browser from following
    if(booleanVar){
        var anchor = document.createElement('a');
        anchor.href = this.props.download_url;
        anchor.target = '_blank';
        anchor.download = this.props.file_name;
        anchor.click();
    }
    else window.location.href = href;
});

For references: Force download through js or query

Upvotes: 1

Related Questions