-1

Currently I have an <a> tag which has already declared download attribute, like this:

<a href="123.png" download >Download it!</a>

Which the tag above, I can download the image from an url when clicking on the link. Now I have a button on my page, like this :

<button>Download by using button!</button>

Is there any way to let the user download not by clicking on the link but by clicking on the button instead.

My purpose is just for making an auto code that can download all the image with a specified class on a html page.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
huy nguyen
  • 1,381
  • 2
  • 11
  • 18
  • This answer may be helpful http://stackoverflow.com/questions/11620698/how-to-trigger-a-file-download-when-clicking-an-html-button-or-javascript – Jovin Thariyath Jan 16 '16 at 11:17

2 Answers2

0
var el = document.{get you <a> tag by one of methods};
el.dispatchEvent(window.CustomEvent?new CustomEvent('click'):document.createEvent('click')); 

This code may dont worked, but anyway you can use createEvent and dispathEvent to your tag to fire download action

UP: In jQuery it more simple - $('your a tag').trigger('click') but jQuery may mess up in this things, native code will be more robust

jotik
  • 17,044
  • 13
  • 58
  • 123
Darth
  • 1,592
  • 10
  • 19
0

Using native javascript would be something like this:

HTML:

<a id="download-link" href="123.png" download >Download it!</a>

Javascript:

document.getElementById("download-link").click();
iamdeit
  • 5,485
  • 4
  • 26
  • 40