Proper Link Handling With PushState

Adtile Technologies
Adtile Technologies wrote this on

Have you ever come across some web application that uses pushState and doesn’t let you use Cmd + Click to open links in new tabs? I know I have. More worrying is that sometimes these so called links are just div elements, not <a> elements at all. Let’s fix this problem.

We can start with a very simple link:

<a href="/profile">Profile</a>

The value of the href attribute on all internal links is going to start with a slash, so we can react to those. The important thing is that we stay out of the way if any modifier key is being pressed. We can achieve our desired behavior with the following code (using jQuery):

$(document).on("click", "a[href^='/']", function(e) {
  if (!e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey) {

    e.preventDefault();
    // Trigger the route change

  }
});

Now users can expect your application to work just like any other website. Pressing a modifier key while clicking the link will let the browser handle the link without any JavaScript interference. As an added bonus you can even deal with other things here in addition to the route change, such as notifying your web analytics service of a new page view.

Here is the above example with actual route changing (using Backbone.js):

$(document).on("click", "a[href^='/']", function(e) {
  if (!e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey) {

    e.preventDefault();
    var url = $(e.currentTarget).attr("href").replace(/^\//, "");
    app.navigate(url, { trigger: true });

  }
});

Pretty straightforward: We grab the URL from the <a> element, remove the leading slash, and call navigate on our instance of Backbone.Router (here named “app”). The “trigger” option will make it call the route function for the URL we are navigating to.

Update: No longer using rel="internal" on the links, which was my original suggestion. Thanks Alan Hogan for pointing out why it was a bad idea, and Ben Cherry for suggesting a better solution.

Adtile Technologies

About the Author

Adtile is a pioneer and developer of motion-sensing technology for smartphones and tablets. We are working with leading technology companies and Fortune 500 brands.

Read all posts by Adtile.

Follow us on Twitter