views:

217

answers:

5

so that it would be cross browser

+2  A: 

To ensure robust cross-browser support, use a library like jQuery: see keyboard events

Of course, there are other Javascript libraries out there:

Gregory Pakosz
i needs know letters like abs or пошел на
xXx
look at my answer. (заминусованный)
Coyod
@xXx then maybe you have to to edit your question and reformulate in a more elaborate way so that people can help you with more detailed answers
Gregory Pakosz
+2  A: 

Have a look at this site for cross browser inconsistencies http://www.quirksmode.org/js/keys.html

Matt Joslin
Only on the keypress event in some browsers (notably not Firefox).
Tim Down
@Tim Good point - actually I'll take that out.
Matt Joslin
A: 

Use this one:

function onKeyPress(evt){
  evt = (evt) ? evt : (window.event) ? event : null;
  if (evt)
  {
    var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
    if (charCode == 13) 
        alert('User pressed Enter');
  }
}
JCasso
A: 

"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)); 
 })
Coyod
Hey, what's wrong? Here is 2 cases of cross-browser even handler.
Coyod
I didn't downvote, but you've got the wrong event in the first example: you need keypress rather than keydown to get the character typed.
Tim Down
Yeah, my mistake when I tried to explain how to add event on dom-object.
Coyod
+1  A: 

There's a million duplicates of this question on here, but here goes again anyway:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    var charStr = String.fromCharCode(charCode);
    alert(charStr);
};

The best reference on key events I've seen is http://unixpapa.com/js/key.html.

Tim Down