I am creating an anchor element using jQuery/Javascript. I am using this method:
var a = document.createElement('a');
a.href = '/files/target.pdf';
a.download = true;
But how can I perform a click event on it without appending/prepending it to the DOM? My intention is pretty simple. I want to let the user download a file instead of opening it in browser and that's why I want to avoid the window.location = '/files/target.pdf';
function.
Please help me.
Thanks.
Well, you can trigger the "click" like this:
var anchor = document.createElement('a');
anchor.href = 'http://gutfullofbeer.net/mozilla.pdf';
anchor.download = true;
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
anchor.dispatchEvent(evt);
However, when I do that in Firefox, I get a PDF file that's shown in Firefox's built-in PDF viewer. (Chrome seems to do the "right" thing, which is to show a "Save ..." dialog.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With