Skip to content

Instantly share code, notes, and snippets.

@mohamedmansour
Created February 27, 2011 08:22
Show Gist options
  • Save mohamedmansour/846017 to your computer and use it in GitHub Desktop.
Save mohamedmansour/846017 to your computer and use it in GitHub Desktop.
Keyboard State Handler
<!DOCTYPE html>
<!-- Simple keyboard state handler, Vincent Scheib. -->
<!-- Adapted from http://www.cryer.co.uk/resources/javascript/script20_respond_to_keypress.htm -->
<html><body>
<table border="1" cellspacing="0">
<tbody><tr>
<th>KeyDown</th>
<th>KeyUp</th>
<th>KeyPress</th>
</tr>
<tr>
<td id="td-keydown" style="width: 12em" class="center">keyCode: 69 'E'</td>
<td id="td-keyup" style="width: 12em" class="center">keyCode: 69 'E'</td>
<td id="td-keypress" style="width: 12em" class="center">keyCode: 101 'e'</td>
</tr>
</tbody></table>
<pre id="keyStateDisplay">No key events captured yet.</pre>
<script type="text/javascript">
var keyStateDict = {};
function displayKeyState()
{
var s = document.getElementById("keyStateDisplay");
var ss = JSON.stringify(keyStateDict);
var re = new RegExp("[,{}] *", "g");
ss = ss.replace(re, "\n");
s.innerHTML = ss;
}
function GetCodeFor(e)
{
if ((e.charCode) && (e.keyCode==0))
{
return e.charCode;
} else {
return e.keyCode;
}
}
function GetDescriptionFor(e)
{
var result, code;
if ((e.charCode) && (e.keyCode==0))
{
result = "charCode: " + e.charCode;
code = e.charCode;
} else {
result = "keyCode: " + e.keyCode;
code = e.keyCode;
}
if (code == 8) result += " BKSP"
else if (code == 9) result += " TAB"
else if (code == 46) result += " DEL"
else if ((code >= 41) && (code <=126)) result += " '" + String.fromCharCode(code) + "'";
if (e.shiftKey) result += " shift";
if (e.ctrlKey) result += " ctrl";
if (e.altKey) result += " alt";
return result;
}
function MonitorKeyDown(e)
{
if (!e) e=window.event;
var cell = document.getElementById("td-keydown");
d = GetDescriptionFor(e);
cell.innerHTML = d;
keyStateDict[GetCodeFor(e)] = d + " == DOWN";
displayKeyState();
return false;
}
function MonitorKeyUp(e)
{
if (!e) e=window.event;
var cell = document.getElementById("td-keyup");
d = GetDescriptionFor(e);
cell.innerHTML = d;
keyStateDict[GetCodeFor(e)] = d + " == up";
displayKeyState();
return false;
}
function MonitorKeyPress(e)
{
if (!e) e=window.event;
var cell = document.getElementById("td-keypress");
cell.innerHTML = GetDescriptionFor(e);
return false;
}
document.onkeydown = MonitorKeyDown;
document.onkeyup = MonitorKeyUp;
document.onkeypress = MonitorKeyPress;
</script>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment