0

Below dynamic part is getting created where i can see the Download link . Now i want to write an on click event listener so that i can download the image . As the domain is different i cannot actually use the tag .

    <table id="example" class="table table-striped dataTable no-footer" style="width: 100%;" aria-describedby="example_info">
    <tbody>

// dynamic part

    <tr class="odd"><td class="sorting_1">971122</td><td>12/23/1221</td><td>123123</td><td>I</td>
    <td><a id="downloadImage" href="https://sample-videos.com/img/Sample-jpg-image-50kb.jpg" >Download</a></td>
    <td> <button type="button" id="delete" class="btn btn-sm btn-outline-secondary">Delete</button> <button type="button" id="edit" class="btn btn-sm         btn-outline-secondary">Edit</button></td></tr>
    
    
    
    </tbody></table>        

Something like this ,pls help . Please note more or rows can be added dynamically . I tried using download with tag but as the domain is different it is redirecting and not downloading.

    $('#example').on('click', function () {

       // get the id of the this or current a tag
       // get the attribute href of the a
       // download the image 
       
    );
Mohit H
  • 927
  • 3
  • 11
  • 26

1 Answers1

0

You need to prevent the default anchor click action first and then create a new anchor link which can be clicked programatically.

You can try below code.

function downloadURI(uri, name) {
  let link = document.createElement("a");
  link.download = name;
  link.href = uri;
  link.click();
}

$(document).on('click', '#example a', function(e) {
  e.preventDefault();
  const href = $(this).attr('href');
  const name = href.split('/').reverse()[0];
  let blob = new Blob([href]);
  let url = window.URL.createObjectURL(blob);
  downloadURI(url, name);
  window.URL.revokeObjectURL(url);
});
CodeThing
  • 2,580
  • 2
  • 12
  • 25