Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the keypress

In an input box or contenteditable=true div, how can I modify a keypress for the letter "a" to return a keybress for the letter "b"? I.e., every time you type the letter "a" in the div, the output is actually the letter "b".

I'm not that concerned with a solution that works in IE--just one that works in Safari, Chrome, & FF.

In Chrome, I can see that a keypress event has the properties "charCode", "keyCode", and "which", all of which get assigned the keypress event number. If I fire an event on a keypress, I can modify these values, but I can't figure out what to return so that the actual key that gets typed is different. For example:

$(window).keypress(function(e){  //$(window) is a jQuery object     e.charCode = 102;     e.which = 102;     e.keyCode = 102;     console.log(e);     return e; }); 

I can also see that along with charCode, which, and keyCode, there is also an "originalEvent" property which in turn also has these properties. However, I haven't been able to modify those (I tried with things like e.originalEvent.charCode = 102).

like image 514
maxedison Avatar asked Jan 05 '11 14:01

maxedison


People also ask

What is the difference between JQuery Change () and keypress () events?

The change event occurs if the value has been changed when the element loses focus. The keypress event occurs every time you press down and release a (non control) key.

Does keypress work on mobile?

It works on computers, but not on mobile..


1 Answers

You can't change the character or key associated with a key event, or fully simulate a key event. However, you can handle the keypress yourself and manually insert the character you want at the current insertion point/caret. I've provided code to do this in a number of places on Stack Overflow. For a contenteditable element:

  • Need to set cursor position to the end of a contentEditable div, issue with selection and range objects

Here's a jsFiddle example: http://www.jsfiddle.net/Ukkmu/4/

For an input:

  • Can I conditionally change the character entered into an input on keypress?

  • show different keyboard character from the typed one in google chrome

Cross-browser jsFiddle example: http://www.jsfiddle.net/EXH2k/6/

IE >= 9 and non-IE jsFiddle example: http://www.jsfiddle.net/EXH2k/7/

like image 111
Tim Down Avatar answered Sep 28 '22 00:09

Tim Down