Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set download attribute on dynamically displayed image

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?

like image 536
Wesley Smith Avatar asked Dec 27 '22 00:12

Wesley Smith


2 Answers

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.

like image 185
Jonathan Naguin Avatar answered Jan 14 '23 06:01

Jonathan Naguin


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 !

like image 41
Bigood Avatar answered Jan 14 '23 06:01

Bigood