1

I'm trying to make a virtual keyboard with jQuery.

When I press 'a' in the given textarea, suppose that 'z' should be written instead.

In textarea, I found the whole steps of typing a letter is given by

keyDown event → keyPress event → letter typed in textarea → keyUp event

In my code, I detected the letter in keyPress event and in that event, if the letter was 'a', I added 'z' in textarea using .val() method.

If we have the initial string hello in textarea, after keyPress event, we have helloz. Then, before keyUp event occurs, textarea became helloza. So I deleted the last letter, 'a' in keyUp event.

This looks great, and also works well. But, the problem is TIME DELAY.

Since steps I wrote above takes a second, 'a' appears quite a while in the textarea.

But the virtual keyboard in Google Translator does not show the original letter.

How can I do this?

Analysis
  • 240
  • 1
  • 11

2 Answers2

2

Try calling event.preventDefault() in the keyPress event handler.

soulprovidr
  • 754
  • 3
  • 14
2

As mentioned, you can use preventDefault() to prevent it from being displayed in your text box, then if you are looking for practical way to get the pressed key's character (instead of the char code), you can do :

$('#txt').on('keypress', function (e) {
    var pressedKey = String.fromCharCode(e.keyCode);
    var $txt = $('#txt');
    e.preventDefault();
    if (pressedKey == 'a') {
        $txt.val($txt.val() + 'z');
     }
});

Here is demo: http://jsfiddle.net/82meao9v/1/

Caner Akdeniz
  • 1,862
  • 14
  • 20