-
Notifications
You must be signed in to change notification settings - Fork 0
/
keytest.html
96 lines (85 loc) · 2.95 KB
/
keytest.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<!DOCTYPE html>
<html>
<head>
<title>Key test</title>
<style>
body { font-family: monospace; }
</style>
</head>
<body>
<div id="keydown">Press any key to begin testing</div>
<div id="keypress"> </div>
<button id="clearEvents">Clear</button>
<label><input type="checkbox" id="captureAll" checked="1" /> Capture all</label>
<div id="events"></div>
<script type="text/javascript">
var keyDownDiv = document.getElementById('keydown');
var keyPressDiv = document.getElementById('keypress');
var eventsDiv = document.getElementById('events');
//var showCodes = document.getElementById('showCodes');
var captureAll = document.getElementById('captureAll');
var lastTextElem = null;
var lastText = '';
function getKeyText(evt) {
let keytxt = evt.key;
if (keytxt == " ") keytxt = "Space";
if (evt.shiftKey && evt.key != 'Shift') keytxt = 'Shift+' + keytxt;
if (evt.altKey && evt.key != 'Alt') keytxt = 'Alt+' + keytxt;
if (evt.ctrlKey && evt.key != 'Control') keytxt = 'Ctrl+' + keytxt;
return keytxt;
}
function getKeyCode(evt) {
let keytxt = '';
if (evt.which) {
keytxt += ` (code ${evt.which}`;
if (32 <= evt.which && evt.which <= 126) {
keytxt += ` [${String.fromCharCode(evt.which)}]`;
}
keytxt += ')';
}
return keytxt;
}
function addEvent(txt) {
if (txt.length > 1) {
lastTextElem = null;
lastText = '';
let elem = document.createElement('span');
elem.innerText = ` ${txt} `;
eventsDiv.appendChild(elem);
} else {
lastText += txt;
if (!lastTextElem) {
lastTextElem = document.createElement('span');
eventsDiv.appendChild(lastTextElem);
}
lastTextElem.innerText = '"' + lastText + '"';
}
}
function checkPreventDefault(evt) {
if (captureAll.checked)
evt.preventDefault();
}
function rpt_keydown(evt) {
let txt = getKeyText(evt);
addEvent(txt);
txt += getKeyCode(evt);
keyDownDiv.innerText = `Key down: ${txt}`;
checkPreventDefault(evt);
}
function rpt_keypress(evt) {
let txt = getKeyText(evt);
txt += getKeyCode(evt);
keyPressDiv.innerText = `Key press: ${txt}`;
checkPreventDefault(evt);
}
function clearEvents() {
lastTextElem = null;
lastText = '';
eventsDiv.innerHTML = '';
}
document.addEventListener('keypress', rpt_keypress, false);
document.addEventListener('keydown', rpt_keydown, false);
document.getElementById('clearEvents').addEventListener('click', clearEvents);
</script>
</body>
</html>