set download attribute on dynamically displayed image
10,960
Solution 1
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.
Solution 2
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);
Related videos on Youtube
Author by
Wesley Smith
I enjoy working on PHP applications created with MySQL, Laravel, and Vue.js for fun or profit. Mostly, I love to build things that solve problems
Updated on June 04, 2022Comments
-
Wesley Smith almost 2 years
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?
-
Wesley Smith almost 11 yearsAh, needed the link, perfect. Thank you!