Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting IME input before enter pressed in Javascript

I'm not even sure if this is possible, so apologies if it's a stupid question.

I've set up an keyup callback through jQuery to run a function when a user types in an input box. It works fine for English.

However when inputting text in Japanese/Korean/Chinese, the function isn't called until the user confirms their text.

Is it possible to detect that they've started typing, and access their as-yet unfinished text?

I'm thinking maybe it's an OS-level thing so Javascript doesn't have access to it.

Edit: I just realised that this works in Chrome and Safari, but not in Firefox (not had a chance to try it on Windows yet). So Chrome calls keyup and it's possible to get the text. But I'm still having the above problem in Firefox.

like image 385
benui Avatar asked Sep 06 '11 08:09

benui


2 Answers

The compositionstart, compositionupdate and compositionend events might be helpful. They help you detect when IME input is being used.

For example, consider using an IME to type か (ka) in Japanese.
The following events (in the order shown) would be fired:

  • k (IME visible) keydown, compositionstart, compositionupdate, compositionend, input
  • a (IME visible), compositionstart, compositionupdate, compositionend, input
  • enter (IME closed) keydown, input

Notice that the compositon events are only fired when the IME is visible (before enter is pressed). Also notice that the keypress event is not fired. This is only fired for non-IME input.

To access the user's unfinished text, you can use the data property of the event.

$('#input').on('compositionupdate', function(e) {
    console.log(e.data);
});

For more info see MDN: compositionstart, compositionupdate, compositionend, InputEvent.

like image 114
James Lawson Avatar answered Nov 10 '22 15:11

James Lawson


This is a known issue in Firefox, and what browsers should be doing isn't clear.

A possible method for working around this problem is demonstrated here, where the text field is polled for changes to the text (rather than relying on events).

like image 5
一二三 Avatar answered Nov 10 '22 15:11

一二三