Ori Refael
Ori Refael

Reputation: 3008

jquery simulate click on html anchor tag

I've been trying to simulate click on a tag and this is not working as i need it to. my anchor tag looks like this

<a href="/dl/pic.jpg" target="_blank" download="file.jpg"> Download this pic </a>

a normral $("a").click() or trigger('click') wont work here.Any ideas? EDIT I need to trigger a click on this Anchor tag and causing the file to download, i dont need to add another onClick function.

Upvotes: 3

Views: 7624

Answers (4)

Nick
Nick

Reputation: 4212

add the path to the file to be downloaded to the hrefattribute not to download attribute

<a href="/dl/file.jpg" target="_blank"> Download this pic </a>

Upvotes: 0

Deepu Madhusoodanan
Deepu Madhusoodanan

Reputation: 1505

You can achieve this using JavaScript itself by adding an id attribute

<a id="download" href="/dl/pic.jpg" download="file.jpg"> Download this pic </a>

document.getElementById("download").click();

Upvotes: 1

Tomer
Tomer

Reputation: 17930

Few options here:

  1. The link is added dynamically, in that case binding click won't work, you need to do something like this:

     ('#linkContainer').on('click','a',function(){//do stuff});
    
  2. the click does work, but since its an a tag, it has a default behaviour and it goes to the href, so you need to add in the function e.preventDefault

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

Using native js click event works:

http://jsfiddle.net/n6FKg/

$('a').get(0).click();

Upvotes: 9

Related Questions