-1

Sorry if this may seem stupid, but how would I make a JS file that will do something when the user clicks the letter w or some other letter? Again sorry if this is a stupid question...

4 Answers4

1
document.addEventListener("keydown", keyDownEvent, false);

function keyDownEvent(e) {
var keyCode = e.keyCode;

  alert("You have hit some key :"+keycode);

}

you can refer the key codes on google. and accordingly perform some action.

Esha Jain
  • 555
  • 5
  • 16
0

logic: read the ascii value of the key stroke and store it in some variable in if condition compare the stored value to the actual ascii value and if it matches execute the code.This should work

Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49
Naim FS
  • 61
  • 9
0

Do a search on "javascript keypress keydown keyup" on Google and you may start from here.

Johnny
  • 481
  • 4
  • 13
0

Try out something like:

<html>
<script type="text/javascript">
function keyHandler(e){
    if(!e)e=window.event;
    if(!e.which)e.which=e.keyCode;
    if(e.which==87){ /*87 is the keycode for 'w' */
        //do whatever you want
    }
}

if(document.attachEvent){
    document.attachEvent("onkeyup",keyHandler);
}else{
    document.addEventListener("keyup",keyHandler,false);
}
</script>
</html>
kcak11
  • 832
  • 7
  • 19