Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created May 2, 2011 10:36
Show Gist options
  • Save JamieMason/951419 to your computer and use it in GitHub Desktop.
Save JamieMason/951419 to your computer and use it in GitHub Desktop.
Rough snippet of a page-wide key press listener
function _keyEventWasDataEntry (e)
{
var key = e.charCode,
keychar = String.fromCharCode(key);
// Return false if key was;
// 9 tab
// 8 backspace
// 16 shift
// 17 control
// 18 alt
// 91 apple command
// 35 end
// 36 home
// 37 left
// 39 right
// 38 up
// 40 down
// 13 enter
// ...or the alt or control keys were down
return !(/^(9|8|16|17|18|91|35|36|37|39|38|40|13)$/.test(key) || e.ctrlKey || e.altKey);
}
// bind behaviours
$('body').delegate('input:text', 'keypress', function(e)
{
// if user is navigating and not entering data
if (!_keyEventWasDataEntry(e))
{
// allow navigation and quit
return;
}
// if they're entering characters other than numbers and the decimal point
if (String.fromCharCode(e.charCode).search(/[^0-9\.]/) !== -1)
{
// block entry and quit
return e.preventDefault();
}
console.log(String.fromCharCode(e.charCode));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment