Kamafeather
Kamafeather

Reputation: 9845

Trigger a click on <a href="" /> through Javascript (cross-browser solution)

I have an <a href="" class="auto_download" /> and would like to trigger, through Javascript a click (currently using jQuery; but some JS equivalent is ok too).

$('auto_download')[0].click();

Actually it works correctly if the <a href="" /> has a target="_blank" attribute; but the pop-up is blocked from the major browsers.

So, to avoid the issue, I removed the target=_blank" and it now does NOT work anymore. I guess this is related to some security policy of the browsers regarding what can be automatically clicked.

I've read different questions, I've seen many different solutions on SO, but couldn't find one that could be really cross-browser.

Upvotes: 0

Views: 186

Answers (2)

DripDrop
DripDrop

Reputation: 1002

Try pure js:

document.getElementByClassName("auto_download")[0].click();

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

The code you have used,

$('.auto_download').click();

Would actually invoke the click handler attached to it. It wont make a physical click action over it. If you want to make a physical click then do,

$('.auto_download')[0].click();

But this wont be supported in touch device.

Upvotes: 4

Related Questions