contenteditable and input events
contenteditable hands editing to the browser; beforeinput and input describe an edit with an inputType, so an editor can cancel the browser's change, apply it to its own model and render. IME composition and some corrections take another path.
What it is
contenteditable is an HTML attribute that makes an element editable: the browser handles the caret, the selection and the text edits itself. It takes true or the empty string, false, or plaintext-only, which lets the raw text be edited but disables rich formatting; a missing or invalid value is inherited from the parent. An editable element can be focused and takes part in tab order. Pasting into contenteditable="true" keeps the formatting of what was copied, and pasting into plaintext-only drops it.
Two events report the edits. beforeinput fires before the browser modifies the DOM and input fires after, and both are dispatched on the editing host: the contenteditable element, a textarea or a text input element. When editable elements nest, the host is the nearest ancestor whose own parent isn't editable. The beforeinput event is an InputEvent with an inputType that names the intention behind the edit: insertText, deleteContentBackward, insertParagraph, formatBold, insertFromPaste and a long list of others. For insertText the data property holds the plain text about to be inserted. getTargetRanges() returns StaticRange objects for the DOM that will change if the event isn't canceled; in a textarea or input it returns an empty array. beforeinput and getTargetRanges() have been available across browsers since March 2021.
The point of beforeinput is that a web app can override the browser's edit before the DOM tree changes. That is what makes a model-backed editor architecture work: the document lives in a data structure of the editor's own, not in the HTML, and all updates pass through a single point where the editor can inspect them. ProseMirror describes its view as rendering the editor state into an editable DOM node and generating transactions when the user types, with all state updates going through one method. The events were designed with this in mind: the published use cases include an editor that keeps a data model in the background and lets JavaScript render changes to the DOM, and a collaborative editor that renders from user intentions across browsers that express those intentions differently. In that architecture, a keystroke becomes: beforeinput arrives, the handler cancels it, maps the target range to model positions, applies an operation, re-renders the changed part of the DOM, and sets the DOM selection from the model's selection.
host.addEventListener('beforeinput', (e: InputEvent) => {
// Composition and other non-cancelable edits: let the browser write, reconcile later.
if (e.isComposing || !e.cancelable) return;
const [range] = e.getTargetRanges();
// historyUndo and historyRedo carry no target range; this example leaves them to the browser.
if (!range) return;
const from = toModelPos(range.startContainer, range.startOffset);
const to = toModelPos(range.endContainer, range.endOffset);
switch (e.inputType) {
case 'insertText':
dispatch(replaceText(from, to, e.data ?? ''));
break;
case 'deleteContentBackward':
case 'deleteContentForward':
dispatch(replaceText(from, to, ''));
break;
case 'insertParagraph':
dispatch(splitBlock(from, to));
break;
case 'formatBold':
dispatch(toggleMark(from, to, 'bold'));
break;
default:
return; // unknown intent: the browser edits, the input handler reconciles
}
e.preventDefault(); // the model changed; render() will rewrite the DOM and the caret
});
host.addEventListener('input', (e: InputEvent) => {
if (!e.defaultPrevented) reconcileFromDom(); // the browser changed the DOM; fold it into the model
});
host.addEventListener('compositionend', () => reconcileFromDom());Two kinds of edit don't follow that path. The first is composition. An input method editor, the kind used to enter Chinese characters with Pinyin, opens a composition session, announced by compositionstart, updates the uncommitted text through compositionupdate, and finishes with compositionend. While the session is open the browser fires beforeinput with inputType insertCompositionText, and that one is not cancelable by design: the stated goal of Level 2 is for the rest of beforeinput to be cancelable, apart from events raised inside a composition. The second kind is replacement. insertReplacementText describes a change made by a spell checker, autocorrect or a writing suggestion, and it is listed as cancelable. MDN warns that practice is looser: some user changes produce no beforeinput at all, and a correction from a spell checker, an autocomplete, a password manager or an IME can arrive non-cancelable. The details differ by browser and operating system, so an editor that wants control in all cases also handles input and reverts or absorbs what its beforeinput handler didn't see.
When to use it
Reach for contenteditable plus a beforeinput handler when you are building an editor that owns its document model: a schema that allows some structures and not others, an undo history made of operations, or collaborative editing that sends operations to other clients. Those features need each edit as an operation with a position, not as a new HTML blob to diff. Input Events Level 2 was written for this case: its listed problems include that browsers don't handle editing operations the same way and are often buggy at it, and that sites want their own behavior for some operations.
Use the browser's own editing, with plaintext-only, for a title, a caption or an inline rename where you want a caret and native text handling but no formatting. The attribute strips formatting from pasted content. You listen to input and read the text back from the DOM yourself to update your state.
Use inputType as the switch, not the key code. Intentions expressed by keyboard, IME, speech or a similar method are mapped onto the same inputType values following platform conventions, so a word deletion is meant to arrive as deleteWordBackward whatever produced it. Our advice: don't build the switch on keydown, which models keys rather than intentions and has nothing to say about a correction or a dictated phrase.
When not to
When the field is plain text, a textarea or input element is the simpler choice. Both are editing hosts too, so beforeinput and input fire on them as well, with inputType values drawn from the same list, but you read value instead of reconciling a DOM tree, and getTargetRanges() gives you an empty array because there is no DOM to target. You also keep the form control's native behavior instead of rebuilding it.
Don't try to cancel what isn't cancelable. Calling preventDefault() on an insertCompositionText event does nothing useful, and treating composition like typing leaves the model without the composed text while the browser has already put it in the DOM. Check cancelable on the event rather than assuming it from the inputType.
Don't leave contenteditable="true" as a bare input for user text you plan to store. Pasted content keeps its formatting, and nested editable elements are left out of the tab sequence by default, so without a model, a paste handler and sanitizing you can end up storing markup you didn't choose.
Compared
| Approach | Who owns the text | Pick it when | What it costs |
|---|---|---|---|
| The browser; you read | The content is plain text, such as a comment or a search box | No formatting, no inline widgets |
| The browser; you read the text back from the DOM | A title, caption or rename needs a caret but no formatting | Formatting is dropped on paste; you still read your value out of a DOM |
| The browser; you serialize the HTML on | A small, forgiving field where browser differences are acceptable | Browsers edit differently and have bugs; pasted markup must be sanitized; undo and collaboration work on HTML |
| Your model; the DOM is a view | Schema, operation-based undo or collaboration need each edit as an operation | Composition arrives as non-cancelable |
In a picture
Step 1 of 3
A typed letter
The key press reaches the editing host as beforeinput with inputType insertText. The handler cancels it, turns the target range and data into a model operation, renders the changed DOM and sets the DOM selection from the model.