I have a link with href and download attributes:
<a id="lnk" href="data:text/csv;charset=utf-8,1%2C2%2C3" download="my_file.csv">click to download</a>
When I click on it (in Chrome for example) a csv file "my_file.csv" is downloaded as supposed.
Now I want to be able to cause this action programmatically. So using JQuery I am trying to do:
$('#lnk').click();
or
$('#lnk').trigger("click");
but the file is not downloaded.
Here is the code: http://jsbin.com/yereg/3/edit
I could copy the link address from the link and then just use window.open:
window.open('data:text/csv;charset=utf-8,1%2C2%2C3');
but this way I can't set the file name (link does by download="my_file.csv"
attribute). This solution is fine if there is a way to set the file name.
Remark: in my case Chrome and Firefox should be supported. I don't care about the rest of the browsers.
from the jquery documentation:
The click event is only triggered after this exact series of events:
The mouse button is depressed while the pointer is inside the element. The mouse button is released while the pointer is inside the element.
You could resort to calling the JavaScript native event, through
$('#lnk').get(0).click();
Or safer:
var lnk = document.getElementById('lnk');
if (lnk) {
lnk.click();
}
EDIT:
Out of curiosity, I had a look at the jQuery sources how it's done. It turns out that they prevent the native click event of the browser on links in particular on purpose, see the following excerpt from the events.js
in the latest jQuery version (2.1.x), especially the comment:
click: {
[...]
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
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