Is there any reason the following code should not return anything in my console log?!
document.onkeypress = zx();
function zx(){
console.log(event.keyCode);
} // zx
window.onkeypress
also doesn't work.
Other attempts has been made, like these:
document.onkeypress = zx(event);
function zx(event){
console.log(event.keyCode);
} // zx
-
document.onkeypress = zx;
function zx(){
console.log(event.keyCode);
} // zx
Thanks!
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .
Warning The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.
Omit the parenthesis on the call, you do not need to specify them.
Solution:
document.onkeypress = zx;
function zx(e){
var charCode = (typeof e.which == "number") ? e.which : e.keyCode
console.log(charCode);
}
When attaching a function
to event
you don't need the ()
Just do:
document.onkeypress = zx; //note! don't use the ()
function zx(){
console.log(event.keyCode);
} // zx
if you are using chrome try to catch the right value by
function zx(e){
var key = e.which || e.keyCode;
console.log(key);
} // zx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With