Masatoshi Nishiguchi

Detecting enter key pressed in JavaScript

This is my memo on Detecting enter key pressed in JavaScript.

Vanilla JS

// Listen for the enter key press.
document.body.addEventListener( 'keyup', function (e) {
  if ( e.keyCode == 13 ) {
    // Simulate clicking on the submit button.
    submitButton.click();
  }
});

Vanilla JS

// Listen for the enter key press.
document.body.addEventListener( 'keyup', function (e) {
  if ( e.keyCode == 13 ) {
    // Simulate clicking on the submit button.
    triggerEvent( submitButton, 'click' );
  }
});

/**
 * Trigger the specified event on the specified element.
 * https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
 * https://codepen.io/felquis/pen/damDA
 * @param  {Object} elem  the target element.
 * @param  {String} event the type of the event (e.g. 'click').
 */
function triggerEvent( elem, event ) {

  // Create the event.
  var clickEvent = new Event( event );

  // Dispatch the event.
  elem.dispatchEvent( clickEvent );
}

jQuery

$( 'body' ).on( 'keyup', function( evt ) {
  if ( evt.keyCode == 13 ) {
    // Simulate clicking on the submit button.
    $button.trigger( 'click' );
  }
});

My demo

References