Steve
Steve

Reputation: 2588

Run JQuery first and then download files when link clicked

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

Upvotes: 1

Views: 1460

Answers (1)

APAD1
APAD1

Reputation: 13666

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.

Upvotes: 2

Related Questions