Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger the default action/event of a HTML link (anchor element)?

How could one trigger the default action/event of a HTML link (anchor element)? That is to use JavaScript/jQuery to "click" an existing HTML link, as if the user has clicked it.

Just using .click() does not seem to work.

$('#alink').click();
// the nothing happening

For this HTML:

<a id="alink" href="http://google.com" target="_blank">a link</a>

Example fiddle: http://jsfiddle.net/dCfD8/

I'd rather not create a new window in JavaScript (and take care of whatever else needs to be handled when a link is clicked).

like image 400
Qtax Avatar asked Nov 05 '22 15:11

Qtax


1 Answers

You can trigger the click event using a simple trigger method in jQuery.

$('#alink').trigger('click');

Beware though, that even in the event gets fired, the browser will not follow the link href. The only way to follow the href is to actually click it with the mouse yourself.

As far as I know, there is no way to force a link to behave as if it were clicked. You have to change the document location or something like that to actually navigate between pages.

like image 119
Jose Faeti Avatar answered Nov 14 '22 16:11

Jose Faeti