Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.onkeypress is not working, how to fix?

Tags:

javascript

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!

like image 264
Saturnix Avatar asked Apr 16 '12 22:04

Saturnix


People also ask

What is onkeypress in js?

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 .

Is keypress Deprecated?

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.


2 Answers

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);
}

Demo

like image 145
Starx Avatar answered Oct 12 '22 06:10

Starx


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
like image 43
udidu Avatar answered Oct 12 '22 06:10

udidu