I wanted to know how its possible to call a javascript function , as soon as one presses the "return(enter" key,just as in chat systems
3 Answers
The following will do what you want reliably in all major browsers. In IE, you need to get the event object via window.event because it is not passed in as a parameter to the function. Also, using the character code rather than a key code will mean that all enter keys are automatically detected without needing separate detection for each.
For more information on handling key events in JavaScript, I consider http://unixpapa.com/js/key.html the definitive reference.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
if (charCode == 13) {
// Insert Enter handling code here
alert("Enter pressed");
}
};
Comments
window.onkeypress = function(e)
{
switch(e.keyCode e.which) //[2]
{
case NUMPAD_ENTER_KEY_CODE: //[1]
case ENTER_KEY_CODE:
doSomething();
return false;
default:
if (window.console) console.log(e.keyCode e.which); //[2]
return true;
}
}
this is then expandable to work for any number of key codes. You can also try the onKeyDown or onKeyUp events.
Remember to replace ENTER_KEY_CODE with the actual key code (32?). This should print out the keyCodes of any keys that are not enter so that you can figure out their keyCodes.
Edit:
[1] I forgot to mention you may want to detect the numpad-enter keycode.
[2] I forgot that onkeypress uses e.which to store the keyCode
3 Comments
window.event in IE.