click on a link (follow) via jQuery/JavaScript

You might reasonably assume that it would be possible to fire a click event on an "A" element (link) via JavaScript, at which point the browser would fire any click event handlers currently attached, or otherwise just follow the link. But you would be wrong, at least in the case of Firefox.

The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements. - Mozila Documentation

Why is that? It seems that Firefox is following the standard quite strictly, whereas IE has no problems automating link clicks. There may also be a sandbox security argument here, but personally I don't buy that as long as we are allowing JavaScript to fire FORM POSTS.

Regardless, a cross browser solution is needed. At first blush, just setting window.location directly seems to work.

   window.location = $("a#my-link").attr("href");

This naive solution has serious drawbacks; IE will not post a HTTP Referrer header, and the back button may skip pages navigated to this way. However, it may be an acceptable solution depending on your application.

If you have control over the HTML itself, a better solution is to just use FORMs instead. It's trivial to submit a form via jQuery. It's even possible to make the button look somewhat like a HTML link.


<!-- was <a href="/my-link-url">Click me</a> -->
<form id="my-form" action="/my-link-url" action="get">
   <input class="button-link" type="submit" value="Click me" />
</form>

<script>
   // simulate a user clicking the "link"
   $(".button-link").click();

   // you could also just submit the form directly, depending on what's easier
   $("form#my-form").submit();
</script>

<style>
   .button-link {
      background-color:white;
      border:0;
      color:blue;
      text-decoration:underline;
      font-size:1em;
      font-family:inherit;
      cursor:pointer;
   }
</style>



I'm currently working at NerdWallet, a startup in San Francisco trying to bring clarity to all of life's financial decisions. We're hiring like crazy. Hit me up on Twitter, I would love to talk.

Follow @chase_seibert on Twitter