I'm displaying a long list of images from a site on a page with the below code. Id like to be able to use the download HTML5
attribute so that click each image will download it.
Here's what I've tried:
for (var i = 0; i<arlnData.d.length;i++) {
var img = document.createElement('img');
img.src = "https://images.website.com/airvendors/airlines_"+arlnData.d[i].Code+".gif";
img.download ="my image";
//also tried:
//img.src = "https://images.website.com/airvendors/airlines_"+arlnData.d[i].Code+".gif";
document.body.appendChild(img);
var imageCellspace=document.createElement('br');
document.body.appendChild(imageCellspace);
}
Images are displayed fine but clicking to download doesnt work.
What is the proper syntax here?
Try with this:
for (var i = 0; i<arlnData.d.length;i++) {
var img = document.createElement('img');
img.src = "https://images.website.com/airvendors/airlines_"+arlnData.d[i].Code+".gif";
var a = document.createElement('a');
a.href = img.src;
a.download = 'image.gif';
a.appendChild(img);
document.body.appendChild(a);
var imageCellspace=document.createElement('br');
document.body.appendChild(imageCellspace);
}
The download
attribute is for a
, not for img
. Check the documentation.
You have to wrap your <img>
on a <a>
, as the download
attribute is only for anchors.
var img = document.createElement('img');
img.src = "https://images.website.com/airvendors/airlines_"+arlnData.d[i].Code+".gif";
var a = document.createElement('a');
a.href = img.src;
a.download = "My image name";
a.appendChild(img);
document.body.appendChild(a);
See MDN for reference !
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