Skip to content

Instantly share code, notes, and snippets.

@ryanfitzer
Last active July 18, 2019 10:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanfitzer/c976475cbc1d04407433268a5c632c71 to your computer and use it in GitHub Desktop.
Save ryanfitzer/c976475cbc1d04407433268a5c632c71 to your computer and use it in GitHub Desktop.
/**
* Check for common keyboard actions.
*
* @example
* checkInputType( e, 'shift click', fn );
* checkInputType( e, [ 'escape', 'enter' ], fn );
* checkInputType( e, [ 'tab', 'shift tab' ], fn );
*
* @param {Event} e - The event object.
* @param {String|Array} types - The name(s) of the inputs to check.
* @param {Function} [fn] - A function to call if 1 of the `types` match.
*
* @returns {boolean}
*/
export default ( e, types, fn ) => {
types = Array.isArray( types ) ? types : [ types ];
const input = {
// Event Types
click: e.type === 'click',
keydown: e.type === 'keydown',
keypress: e.type === 'keypress',
keyup: e.type === 'keyup',
// Modifier Keys
alt: e.altKey,
command: e.metaKey,
control: e.ctrlKey,
shift: e.shiftKey,
// Non-Modifier Keys
arrowleft: e.keyCode === 37,
arrowright: e.keyCode === 39,
arrowup: e.keyCode === 38,
arrowdown: e.keyCode === 40,
enter: e.keyCode === 13,
escape: e.keyCode === 27,
space: e.keyCode === 32,
tab: e.keyCode === 9
};
const check = ( inputs ) => inputs.split( ' ' ).every( ( action ) => input[ action ] );
const result = types.some( ( type ) => check( type ) );
if ( result && fn ) fn( e, result );
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment