Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery or html to download image onclick or with link

I have an image that I want the user to click on to be able to download ( save it ).

When currently clicked, the download box pops up with the image.jpg tag and lets the user save it.

I am using HTML:

<a href="folio/1.jpg" download><img src="folio/1.jpg"/></a>

This works well, but I have a lot of images, is there a way to use jQuery to do something like

jQuery(function($){
$("a").prop("href", "(this)")
});

to download the image without having to type it in twice so it looks like this:

<a href="" download><img src="folio/1.jpg"/></a>

I am trying to simplify the coding to make it easy to click on the image to download it rather than to have to right click to save it.

Thanks for your help.

like image 580
AlwaysLearning Avatar asked Jan 29 '26 19:01

AlwaysLearning


1 Answers

This would apply to every single image on your page which is the direct child of an anchor, but you could use:

$('a > img').each(function(){
  var $this = $(this);
  $this.parent('a').attr('href', $this.attr('src'));
});

But it would do the job.

Only thing is though, users with JS disabled will see an anchor with an empty href. The following would achieve the same end result with the added benefit of simplifying your code (cleaner HTML) and adding graceful degradation:

<img src="folio/1.jpg" class="downloadable" />

and

$('img.downloadable').each(function(){
  var $this = $(this);
  $this.wrap('<a href="' + $this.attr('src') + '" download />')
});

See it in action: http://jsfiddle.net/MW9E4/1/

like image 81
Josh Davenport-Smith Avatar answered Jan 31 '26 08:01

Josh Davenport-Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!