Skizit
Skizit

Reputation: 44862

Javascript event listeners?

I find myself looking to add a listener for a particular key, is there a list somewhere of all of the characters which I can listen for? What exactly can and can I not listen for? Surely there is some sort of limit?

Upvotes: 1

Views: 1132

Answers (3)

Tim Down
Tim Down

Reputation: 324707

If you're interested in listening for a particular character being typed, use the keypress event. You can listen for any character, and obtain the character pressed by its character code. For example, the following illustrates how you can do this for printable keys in all major browsers:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.which || evt.keyCode;
    alert("Character typed: " + String.fromCharCode(charCode));
};

If you're interested in listening for a particular physical key being pressed, use the keyup and/or keydown events and read up about key codes at the definitive reference for all things key-event-related in JavaScript: http://unixpapa.com/js/key.html

Upvotes: 0

Peter Porfy
Peter Porfy

Reputation: 9040

You are able to listen to onkeypress, onkeyup, onkeydown keyboard events on a DOM object. Then you can determine which key raised the event (from the event args).

Check out this page: http://www.w3schools.com/jsref/event_onkeypress.asp for example

Upvotes: -1

alex
alex

Reputation: 490597

Here is a list of the charCodes.

Upvotes: 2

Related Questions