Document.onkeypress not working

Is there a reason why the following code should not return anything in my console log ?!

document.onkeypress =  zx();


function zx(){
console.log(event.keyCode);
} // zx

window.onkeypress also does not work.

Other attempts were made, for example:

document.onkeypress =  zx(event);


function zx(event){
console.log(event.keyCode);
} // zx

-

    document.onkeypress =  zx;


    function zx(){
    console.log(event.keyCode);
    } // zx

Thank!

+5
source share
4 answers

Omit the brackets in the call, you do not need to specify them.

Decision:

document.onkeypress =  zx;
function zx(e){
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode
    console.log(charCode);
}

Demo

+10
source

When installed functionin eventyou do not need()

Just do:

document.onkeypress =  zx; //note! don't use the ()

function zx(){
    console.log(event.keyCode);
} // zx

If you use chrome, try to catch the correct value

function zx(e){
    var key = e.which || e.keyCode;
    console.log(key);
} // zx
+2
source

try it

document.onkeypress = displayunicode;
function displayunicode(event){
    var charCode = (typeof event.which == "number") ? event.which : event.keyCode
    console.log(charCode )
}

This will work.

+1
source

Your function should define an "event".

// assign a reference to zx; but don't call zx
document.onkeypress =  zx;

// event needs to be defined
function zx(event){
    console.log(event.keyCode);
}

keyCode will sometimes be 0

See this page: event.keyCode on MDN

You probably want to use event.which

    document.onkeypress = zx;
    function zx(event) {
        console.log(String.fromCharCode(event.which));
    }
-1
source

All Articles