Skip to content Skip to sidebar Skip to footer

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?

Solution 1:

Solution 2:

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

Solution 3:

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

Post a Comment for "Javascript Event Listeners?"