jQuery – Programmatically clicking a link and forcing the default action

Supposed you wanted to trigger the click on a link programmatically via jQuery, the following will likely be the first thing you try.

Suppose your link is like: <a id="foo" href="http://mysite.com">Hello</a>

Your code would be: $('#foo').trigger('click'); or $('#foo').click();

Unfortunately, the above won’t work.

You might then attempt to add a dummy event handler that returns true in the hope that it will cause the default action to take place. That wont work too.

A technique that works

Fortunately, there is one technique that works. We can dynamically create a form element with the href of the link we want to click as its action attribute, and then trigger a submit on this form. It goes like:

var a = $('#foo');

// create a temporary form with the href of the link as action and method as get.
  .attr('id', 'dummyForm')
  .attr('action', a.attr('href'))
  .attr('target', a.attr('target'))
  .attr('method', 'get')
  .submit(); // submit it

setTimeout(function() {
  $('#dummyForm').remove(); // remove the temp form
}, 100);

Demo: http://jsfiddle.net/m39rv/

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>