Jin
Jin

Reputation: 932

Trigger click event for appended anchor tag

I append an <a> tag with a href with a download attribute.

$('<a>Download</a>').attr({
    download: 'testing.svg',
    href: dataUrl,
    id: 'download',
    name: 'test'
    // style:'display:none'
}).appendTo("body");

This is my code and I want to trigger the click event:

$('#download').trigger( "click" );

This is not working because it is an appended element.

I tried to use window.open(href,'_blank'); but if I run this statement, the file is not downloading. It just opens a new tab.

How can I download file without redirect?

Upvotes: 3

Views: 1000

Answers (2)

mike_t
mike_t

Reputation: 2691

Try something like this:

 $(document).ready(function(){
   var dataUrl = "https://upload.wikimedia.org/wikipedia/commons/8/88/Inkscape_vectorisation_test.svg"
   $dnl_link = $('<a>Download</a>').attr({
        download:'testing.svg',
        href:dataUrl,
        id:'download',
        name: 'test',
        
    })
    $dnl_link.appendTo("body");
 
  $("#download")[0].click();
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>

Upvotes: 1

Vipin Kumar
Vipin Kumar

Reputation: 6546

JQuery trigger doesn't support download. Please use following code to trigger download.

$('#download').get(0).click();

Upvotes: 1

Related Questions