How to find out what character key is pressed?

xXx picture xXx · Dec 4, 2009 · Viewed 224.3k times · Source

I would like to find out what character key is pressed in a cross-browser compatible way in pure Javascript.

Answer

Coyod picture Coyod · Dec 4, 2009

"Clear" JavaScript:

<script type="text/javascript">
  function myKeyPress(e){
    var keynum;

    if(window.event) { // IE                    
      keynum = e.keyCode;
    } else if(e.which){ // Netscape/Firefox/Opera                   
      keynum = e.which;
    }

    alert(String.fromCharCode(keynum));
  }
</script>

<form>
  <input type="text" onkeypress="return myKeyPress(event)" />
</form>

JQuery:

$(document).keypress(function(event){
  alert(String.fromCharCode(event.which)); 
});