Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a variable using document.createElement('a') and apply click on it without appending it to DOM

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.

like image 540
Phoenix Avatar asked May 18 '14 13:05

Phoenix


1 Answers

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.)

like image 85
Pointy Avatar answered Oct 30 '22 14:10

Pointy