Reputation: 197
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.
Upvotes: 3
Views: 29000
Reputation: 5511
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/
Upvotes: 5