akietta
akietta

Reputation: 381

Using javascript how to log keyboard events?

<input type="text"></input>

<script>
var a = document.getElementsByTagName('input')[0];
a.onkeypress = function(evt) {
  this.evt = evt || event;
var b = String.fromCharCode(evt.keyCode);
 while(forEach(evt) {
     alert("You pressed " + b);
   }
};
</script>

This doesn't seems to be working. It should always alert the key when user presses a key. The browser here is Chrome.

Upvotes: 1

Views: 1493

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

It's not working because you're calling a function you don't define (forEach), here:

while(forEach(evt) {
//    ^

If you look in the JavaScript console, you'll see an error related to that.

Also, you don't want to assign to an evt property on this:

this.evt = evt || event; // <== Don't do this

Just use the argument:

evt = evt || event;

And there's no reason for a loop if you're going to alert every keypress individually.

Also, input elements don't have closing tags. It should just be:

<input type="text">

or (in XHTML, and optionally in HTML):

<input type="text"/>

not:

<input type="text"></input>

And finally, note that some browsers use which for the keycode, others use keyCode. You can use || to use whichever the browser supplies:

String.fromCharCode(evt.which || evt.keyCode)

Here's a minimal update: Live Copy | Live Source

<input type="text">
<script>
var a = document.getElementsByTagName('input')[0];
a.onkeypress = function(evt) {
  evt = evt || event;
  alert("You pressed " + String.fromCharCode(evt.which || evt.keyCode));
};
</script>

Upvotes: 2

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

There is no need for a while loop. Simply grab the key in a cross browser compliant manner, find its char equivalent and alert it.

var a = document.getElementsByTagName('input')[0];
a.onkeypress = function(event) {
  //e.which & e.keyCode are for cross browser compliance
  alert(String.fromCharCode(event.keyCode || event.which)); 
};

Working Example http://jsfiddle.net/VZEQe/

Upvotes: 2

Related Questions