Composition Events in JavaScript

This post explains composition events in JavaScript, including use cases, behavior, and references to help you understand input handling.

Feb 3, 2022 · 2 min read · 258 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

I often use Vimium in Chrome to search bookmarks. Some bookmarks are Chinese and some are English, so I need to switch input methods. I noticed Vimium searches in real time based on input characters, regardless of whether an IME is in use. I hadn’t encountered this in development, so I decided to understand it properly.

Can JS get the current input method name or temporarily switch input method?

The answer is no for both. JS cannot access input method information, nor can it change it. Some pages can prompt whether you’re in Chinese/English input mode by observing input events and characters.

What about Chrome extensions like Vimium? Besides JS, extensions have some Chrome App capabilities, but they still cannot modify input methods.

Input events in JS: input and composition

In JS there are these events:

  • input
  • composition
    • compositionstart / compositionupdate / compositionend

Whenever a user inputs something, the input event fires. Even with a Chinese IME, input fires in real time.

Composition events only fire when using IMEs or other multi-key character input. They trigger compositionstart, compositionupdate, and compositionend in sequence.

Vimium listens to input events, which is why it keeps searching continuously.

Note: InputEvent has an isComposing property, which tells you whether you are currently composing (e.g., in a Chinese IME). This is very useful.

My understanding

Input can be direct or indirect. For English words, keyboard input is the final output. For Chinese, you type weixin and then the IME converts it to wechat. That is indirect/composed input. This explains why JS has composition events.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover