April 16, 2012

document.onkeypress not working

Question by Saturnix

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!

Answer by Starx

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!