Last Updated: January 28, 2019
·
9.473K
· danielpclark

Map [Enter] key to work like the [Tab] key

Map [Enter] key to work like the [Tab] key

I've rewritten Andre Van Zuydam's answer, which didn't work for me, in jQuery. This caputures both <kbd>Enter</kbd> and <kbd>Shift</kbd>+<kbd>Enter</kbd>. <kbd>Enter</kbd> tabs forward, and <kbd>Shift</kbd>+<kbd>Enter</kbd> tabs back.

I've also rewritten the way self is initialized by the current item in focus. The form is also selected that way. Here's the code:

// Map [Enter] key to work like the [Tab] key
// Daniel P. Clark 2014
// MIT License

// Catch the keydown for the entire document
$(document).keydown(function(e) {

  // Set self as the current item in focus
  var self = $(':focus'),
      // Set the form by the current item in focus
      form = self.parents('form:eq(0)'),
      focusable;

  // Array of Indexable/Tab-able items
  focusable = form.find('input,a,select,button,textarea').filter(':visible');

  function enterKey(){
    if (e.which === 13 && !self.is('textarea')) { // [Enter] key

      // If not a regular hyperlink/button/textarea
      if ($.inArray(self, focusable) && (!self.is('a')) && (!self.is('button'))){
        // Then prevent the default [Enter] key behaviour from submitting the form
        e.preventDefault();
      } // Otherwise follow the link/button as by design, or put new line in textarea

      // Focus on the next item (either previous or next depending on shift)
      focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();

      return false;
    }
  }
  // We need to capture the [Shift] key and check the [Enter] key either way.
  if (e.shiftKey) { enterKey() } else { enterKey() }
});

The reason 'textarea'

is included is because we "do" want to tab into it. Also, once in, we don't want to stop the default behavior of <kbd>Enter</kbd> from putting in a new line.

The reason 'a' and 'button'

allow the default action, "and" still focus on the next item, is because they don't always load another page. There can be a trigger/effect on those such as an accordion or tabbed content. So once you trigger the default behavior, and the page does its special effect, you still want to go to the next item since your trigger may have well introduced it.