window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Should do nothing if the default action has been cancelled
}
var handled = false;
if (event.key !== undefined) {
// Handle the event with KeyboardEvent.key and set handled true.
} else if (event.keyIdentifier !== undefined) {
// Handle the event with KeyboardEvent.keyIdentifier and set handled true.
} else if (event.keyCode !== undefined) {
// Handle the event with KeyboardEvent.keyCode and set handled true.
}
if (handled) {
// Suppress "double action" if event handled
event.preventDefault();
}
}, true);
element.keydown((event) => {
var symbolPressed;
//cross browser
if (event.key !== undefined) {
symbolPressed = event.key; //Here control characters represented as String like: ArrowUp
if (symbolPressed.length > 1) return; //filter out control characters
} else if (event.keyCode !== undefined) {
symbolPressed = String.fromCharCode(event.keyCode); //Here control chars represented as one char string
}
//Update this regex if you need other characters
if (!symbolPressed.match(/[A-z0-9\s]/)) return;
console.log(symbolPressed);
});
function myKey(event){
var keycode = event.keyCode; //key code variant 1, not recomendate
var keywhic = event.which; //key code variant 2, nice worked
var unicode = event.key; //string name code, nice worked
var chacode = event.charCode; //works onkeypress="myKey(event)"
var metakey = event.metaKey; //true false, winKey or macComand
document.getElementById("demo").innerHTML = keycode+" "+keywhic+" "+unicode+" "+chacode+" "+metakey;
}
<!DOCTYPE html>
<html>
<body onkeydown="myKey(event)"> <!--onkeypress="myKey(event)"-->
<h1 id="demo">Keyboard Buttons click me and test the keyboard</h1>
<script>
//function myKey(event){
//paste code
//}
</script>
</body>
</html>