Events in contenteditable

Understanding the event lifecycle when users interact with contenteditable elements.

Event order

When a user types in a contenteditable element, events fire in a specific order. The exact order can vary by browser and input method.

  1. keydown – Fires when a key is pressed
  2. beforeinput – Fires before input is committed
  3. compositionstart – Fires when IME composition begins
  4. compositionupdate – Fires during IME composition (may fire multiple times)
  5. compositionend – Fires when IME composition completes
  6. input – Fires after the DOM has been updated

Key events

beforeinput

Fires before input is committed to the DOM. Allows you to prevent or modify the default behavior. Browser support varies by version.

element.addEventListener('beforeinput', (e) => {
  if (e.inputType === 'insertText') {
    // Modify or prevent the input
    e.preventDefault();
  }
});

input

Fires after the DOM has been updated with the new content. This is the most reliable event for detecting changes, but you cannot prevent the change at this point.

element.addEventListener('input', (e) => {
  // DOM has already been updated
  console.log(element.innerHTML);
});

Composition events

Fired when using Input Method Editors (IME) for languages like Japanese, Korean, or Chinese. These events allow you to track the composition process.

element.addEventListener('compositionstart', (e) => {
  // IME composition started
});

element.addEventListener('compositionupdate', (e) => {
  // Composition in progress
  console.log(e.data); // Current composition text
});

element.addEventListener('compositionend', (e) => {
  // Composition completed
});

Browser differences

Event order varies: The exact order and timing of events differs between browsers, especially for IME composition and special keys (Enter, Backspace, etc.).

beforeinput support: Browser support for beforeinput varies by version. Some older browsers may not support it. Always test in your target browsers and consider keydown or input as fallbacks.

Event duplication: Some browsers may fire events multiple times for a single user action. Always test your event handlers across different browsers.

Related resources