beforeinput Gates Rich Text Edits
The beforeinput event carries an inputType for the pending edit, so a contenteditable can preventDefault formatting commands before they land.
Code
const editor = document.querySelector('[contenteditable]');
// beforeinput fires before the edit lands; inputType names the edit
const allowed = new Set([
'insertText',
'deleteContentBackward',
'deleteContentForward',
'insertParagraph',
]);
editor.addEventListener('beforeinput', (event) => {
if (!allowed.has(event.inputType)) {
event.preventDefault();
console.log('blocked edit:', event.inputType);
}
});
editor.addEventListener('input', () => {
console.log('text now:', editor.textContent);
});How it works
Demo state sits in top-level bindings: editor, allowed.
Points of care
- The import surface (if any) is all standard library, all versioned with the language itself.
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Using it
The demo output is labeled (blocked edit:, text now:), so every line of output can be traced to the operation that made it.
The key statements, annotated
editor.addEventListener('beforeinput', (event) => {
if (!allowed.has(event.inputType)) {
event.preventDefault();
console.log('blocked edit:', event.inputType);
}
});
editor.addEventListener('input', () => {
console.log('text now:', editor.textContent);
});
const allowed = new Set([
'insertText',
'deleteContentBackward',
'deleteContentForward',
'insertParagraph',
]);
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- Does beforeinput Gates Rich Text Edits run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.