1

I have a link which has direct file download URL in it. So when a user click on the link, that file downloads.

Here is the link:

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

I was hoping to run some JQuery before this file downloads. I was able to work a solution, but instead of direct downloading, I am redirected to the video. All I want is to download withouth any redirection. This is what I tried:

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

    var href = this.href;
    //My JS Code
    alert(href);

    event.preventDefault();

   window.location = href;
});

Thanks

Steve
  • 2,546
  • 8
  • 49
  • 94
  • Have you tried to add the `download` attribute to the HTML link? http://caniuse.com/#search=download and https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a – Boldewyn Mar 21 '17 at 15:30

1 Answers1

2

You can add the download attribute to the anchor tag and then just don't use preventDefault();

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

    var href = this.href;
    //My JS Code
    alert(href);

});
<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>

Here's a link for browser compatibility.

APAD1
  • 13,509
  • 8
  • 43
  • 72