Created
May 2, 2011 10:36
-
-
Save JamieMason/951419 to your computer and use it in GitHub Desktop.
Rough snippet of a page-wide key press listener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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