Triggering links from JavaScript using jQuery

Sometimes, you may want to trigger a link (that is, an anchor element) directly from JavaScript. That is, you may want to simulate the user clicking on the link programmatically.

If you’re using jQuery, you’ll no doubt be aware of the click() method which can be used to trigger that event on an object. One would think that executing click() on an anchor element would cause the browser to navigate to the URL, but this isn’t the case. You cannot use jQuery’s click() method to fully trigger or simulate a user clicking on a link.

Instead, click(), when executed on links, only seems to trigger any event handlers attached to the DOM element rather than any default behaviour. I’m not sure if this is the case with other event methods or other DOM elements.

The solution

Instead, the solution is to directly manipulate the window.location object from JavaScript. One would think that since preventing the default action is quite simple (with jQuery’s event.preventDefault()), triggering the default action of a link click would also be. But this isn’t the case. Here’s a simple example on how to simulate a user clicking on a link.