Notebook

Putting the Enter Key in Context

9 Sep 2008 at 6 AM

Traditionally, when user hits Enter while using a form it is submitted to the server for processing. Rich Web 2.0 applications should throw this tradition, users no longer expect this behavior. Instead the context in which the user presses Enter should determine what the application should do.

YouTube Search widget appears in larger form

In an application I'm developing users create blog-like posts with an attached video from YouTube. An AJAX YouTube search widget appears mid-form, allowing visitors search YouTube for an appropriate video. In early user testing I found that people typed a keyword into the search box and hit Enter. What should this do? Hitting enter always submits the form, but in this case the user has focused on the YouTube Widget, viewing it as a separate context from the overall form.

Adding an onkeydown handler to the query field to capture the enter key while the YouTube widget is in focus solves the problem.

function handleEvent(event) {
  // Check for Enter Key
  if (event.which == 13) {
    searchYouTube();
    // return false, the event was handled
    return false;
  }

  // If it is some other key return true
  return true;
}

document.getElementById('youtube-search').onkeydown = handleEvent;

This example won't work in all browsers (you should be using JQuery for this stuff anyway), but you get the point. Hitting enter in a field with a search button next to it should initiate the search, not submit some larger form.

I suspect, in forms containing multiple buttons it might make sense to map the enter key to the nearest one. Though, I'll leave it to you to decide.