Caleb Brown

Caleb Brown

Full-stack Engineer
< Blog

Don't Hijack A User's Intent - An Exercise In JavaScript Usability

Comments

I was working on the NYC.gov's new payment system forms recently and a lot of the interactions were done in overlays. A common convention when writing JavaScript is to listen for an event on an anchor tag, like a click, and cancel the default behavior in the click handler. This allows us to take over the default behavior of the anchor tag and do what we want. For example, we may want to open a gallery in a lightbox instead of navigating to the tag's href.

An example of this interaction is below:

$('a').on('click', handleClick);

function handleClick(e) {
  // Don't use the default behavior
  e.preventDefault();
}
What happens when a user actually wants to open the href in another window?

I often find myself wanting to open links in a new window or tab so I don't lose my place or so I can come back later to the content. However, with this interaction, the developer has chosen to take away that option.

A better solution is to listen for a meta key to see if a user is right clicking and let the default browser behavior proceed.

Using our previous example, that would look like:

$('a').on('click', handleClick);

function handleClick(e) {
  // Look for the meta information in the event
  var metaClick = e.metaKey || e.ctrlKey;
  // Allow the default behavior
  if (metaClick) {
    return true;
  }
  // Don't use the default behavior
  e.preventDefault();
}

When building applications, it's important to look out for opportunities to allow both default behaviors that a user would expect from a browser, while building the functionality you desire.