0

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;
});
Community
  • 1
  • 1
Steve
  • 2,546
  • 8
  • 49
  • 94

3 Answers3

2

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>
APAD1
  • 13,509
  • 8
  • 43
  • 72
  • I am hoping to download the file, only when a person presses "Yes", this would download even when yes button is not yet pressed. – Steve Mar 21 '17 at 20:30
  • No, because if they hit "cancel" then it will fire `event.preventDefault()` which prevents the file from being downloaded. – APAD1 Mar 21 '17 at 21:19
1

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();
    }
});
mehulmpt
  • 15,861
  • 12
  • 48
  • 88
1

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

Community
  • 1
  • 1
Kroneaux Schneider
  • 264
  • 1
  • 2
  • 13