JavaScript Element beforeinput Event

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
DOM event
Instance event

What You’ll Learn

The beforeinput event fires when an <input> or <textarea> value is about to change. Learn addEventListener vs onbeforeinput, InputEvent fields (data, inputType), when preventDefault() works, and how it differs from input—with five examples and try-it labs.

01

Kind

Instance event

02

Type

InputEvent

03

When

Before value changes

04

Handler

onbeforeinput

05

Not on

<select>

06

Status

Baseline widely available

Introduction

When a user types, deletes, or pastes into a text field, the browser is about to update the DOM value. beforeinput gives you a chance to inspect—and often cancel—that change before it happens.

MDN: the event also applies to contenteditable hosts and designMode. Unlike input, it does not fire on <select>.

💡
Beginner tip

Prefer addEventListener("beforeinput", ...). For full control, also listen to input: some edits (autofill, spell-check, IME) may skip a cancelable beforeinput.

Understanding beforeinput

An instance event that signals an upcoming text edit. It answers: “Is the value about to change—and should we allow it?”

  • Fires before <input> / <textarea> (and editable hosts) change.
  • Does not fire on <select> (unlike input).
  • InputEventdata, inputType, isComposing, dataTransfer.
  • Not always cancelable for autofill / spell-check / IME paths.
  • Baseline Widely available on MDN (since March 2021).

📝 Syntax

Use the event name with addEventListener, or set the handler property:

JavaScript
addEventListener("beforeinput", (event) => { });

onbeforeinput = (event) => { };

Event type

An InputEvent (inherits from UIEvent).

Event properties

Property Meaning
data Inserted characters (may be "" for deletions)
inputType Change kind (e.g. insertText, deleteContentBackward)
isComposing true during IME composition (between compositionstart/end)
dataTransfer Rich/plain data for some paste or drag edits

⚖️ beforeinput vs input

Topic beforeinput input
Timing Before the value changes After the value changed
Cancelable? Often (not always) No — already applied
<select> Does not fire Can fire
Best for Validate / block edits early React to the final value

⚠️ Not Every Edit Is Cancelable

MDN notes that not every user modification fires beforeinput, and the event may fire but be non-cancelable—for example autocomplete, spell-check corrections, password-manager autofill, or IME updates (details vary by browser and OS).

To override edit behavior in all situations, also handle input and revert unwanted changes that slipped past beforeinput.

⚡ Quick Reference

Goal Code / note
Listen el.addEventListener("beforeinput", fn)
Handler property el.onbeforeinput = fn
See inserted text event.data
See edit kind event.inputType
Block typing event.preventDefault() when cancelable
Feature-detect InputEvent.prototype.getTargetRanges
MDN status Baseline Widely available (Mar 2021)

🔍 At a Glance

Four facts to remember about beforeinput.

Event type
InputEvent

data + type

Timing
before

Value not updated yet

select
no

Does not fire

Baseline
yes

Widely available

Examples Gallery

Examples follow MDN Element: beforeinput event. Type in the Try It Yourself labs to see the event fire before the field updates.

📚 Getting Started

Register handlers and log the value about to change (MDN logger style).

Example 1 — addEventListener("beforeinput")

MDN idea: log the current value immediately before a new edit is applied.

JavaScript
const input = document.querySelector("input");
const log = document.getElementById("values");

input.addEventListener("beforeinput", (e) => {
  // Value has not changed yet — this is the "before" snapshot
  log.textContent = e.target.value;
});
Try It Yourself

How It Works

Each keystroke fires beforeinput while e.target.value still holds the old text. After the event (if not canceled), the browser applies the change and usually fires input.

Example 2 — onbeforeinput Property

Same idea using the event handler property.

JavaScript
const input = document.querySelector("input");

input.onbeforeinput = (e) => {
  console.log("about to change from:", e.target.value);
  console.log("incoming data:", e.data);
};

// Assigning again replaces the previous onbeforeinput handler.
Try It Yourself

How It Works

Prefer addEventListener when you need multiple listeners or easy removal.

📈 Details, Block & Detect

Inspect InputEvent fields, block digits, and feature-detect support.

Example 3 — Read data and inputType

See what kind of edit is about to happen.

JavaScript
const field = document.getElementById("field");

field.addEventListener("beforeinput", (event) => {
  console.log("inputType:", event.inputType);
  console.log("data:", JSON.stringify(event.data));
  console.log("isComposing:", event.isComposing);
});
Try It Yourself

How It Works

Insertions usually set data to the characters. Deletions often use an empty data string with an inputType like deleteContentBackward.

Example 4 — Block Digits with preventDefault()

Cancel ordinary typing when the incoming character is a digit.

JavaScript
const field = document.getElementById("name");

field.addEventListener("beforeinput", (event) => {
  if (event.data && /\d/.test(event.data)) {
    event.preventDefault();
    console.log("Blocked digit:", event.data);
  }
});

// Letters/spaces insert normally; digits are rejected (when cancelable).
Try It Yourself

How It Works

When the event is cancelable, preventDefault() stops the DOM update. Still pair with input if you must defend against autofill or other non-cancelable paths.

Example 5 — Feature Detection

MDN-style check for modern beforeinput / getTargetRanges support.

JavaScript
function isBeforeInputEventAvailable() {
  return (
    window.InputEvent &&
    typeof InputEvent.prototype.getTargetRanges === "function"
  );
}

console.log("beforeinput available:", isBeforeInputEventAvailable());

if (isBeforeInputEventAvailable()) {
  document.querySelector("input").addEventListener("beforeinput", () => {
    console.log("beforeinput path ready");
  });
} else {
  console.log("Fall back to input + manual validation");
}
Try It Yourself

How It Works

getTargetRanges on InputEvent.prototype is a practical signal that the richer before-input editing APIs are present.

🚀 Common Use Cases

  • Blocking invalid characters before they appear in the field.
  • Building richer editors on contenteditable with early edit control.
  • Inspecting inputType to treat insert vs delete differently.
  • Improving performance by deciding early whether an edit should apply.
  • Pairing with input for a complete “before and after” story.

🔧 How It Works

1

User starts an edit

Type, delete, paste, or format in an editable control.

Intent
2

Browser fires beforeinput

An InputEvent describes the pending change.

Event
3

Your handler may cancel

preventDefault() when the event is cancelable.

Decide
4

Value updates (or not)

If applied, input usually follows with the new value.

📝 Notes

  • MDN: Baseline Widely available (since March 2021).
  • Not Deprecated, Experimental, or Non-standard — no status banner required.
  • Does not fire on <select>; use input / change there.
  • Autofill / spell-check / IME paths may not be fully cancelable via beforeinput.
  • Related learning: beforematch, addEventListener(), JavaScript hub.

Universal Browser Support

beforeinput is marked Baseline Widely available on MDN (since March 2021). Logos use the shared browser-image-sprite.png sprite from this project. Still feature-detect if you rely on getTargetRanges or advanced editable hosts.

Baseline · Widely available

Element beforeinput

Works across modern desktop and mobile browsers for upcoming text edits on inputs, textareas, and many editable hosts.

100% Widely available
Google Chrome Supported · Desktop & Android
Full support
Mozilla Firefox Supported · Desktop & Android
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Opera Supported · Modern versions
Full support
Internet Explorer No beforeinput support
Unavailable
beforeinput Baseline

Bottom line: Use beforeinput to inspect or cancel ordinary typing early; also handle input for autofill and other non-cancelable edits.

Conclusion

beforeinput is the “edit is about to happen” signal for text fields and editable hosts. Inspect data and inputType, cancel when allowed, and keep an input fallback for edits that cannot be blocked early.

Continue with beforematch, addEventListener(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Prefer addEventListener("beforeinput", ...)
  • Read inputType and data before deciding
  • Also listen to input for autofill / IME edge cases
  • Feature-detect when using advanced editing APIs
  • Use change/input for <select>

❌ Don’t

  • Assume every edit is cancelable
  • Expect beforeinput on <select>
  • Skip input if security/validation must always win
  • Confuse with the similarly named input event timing
  • Overwrite onbeforeinput if you need multiple listeners

Key Takeaways

Knowledge Unlocked

Five things to remember about beforeinput

An edit is pending—inspect, cancel when possible, then confirm with input.

5
Core concepts
📄 02

InputEvent

data + type

API
🚫 03

Often cancelable

not always

Caveat
🔎 04

Not on select

use input

Scope
🎯 05

Baseline

widely available

Compat

❓ Frequently Asked Questions

It fires when the value of an <input> or <textarea> is about to be modified. Unlike the input event, it does not fire on <select>. It also applies to contenteditable elements and when document.designMode is on.
No. MDN marks Element beforeinput as Baseline Widely available (since March 2021). It is not Deprecated, Experimental, or Non-standard.
An InputEvent (inherits from UIEvent). Useful properties include data, dataTransfer, inputType, and isComposing.
Often yes for ordinary typing, which lets you override edit behavior before the DOM changes. But not every modification is cancelable — autocomplete, spell-check corrections, password autofill, and some IME updates may fire a non-cancelable event or skip beforeinput. Also handle input and revert unwanted changes when needed.
beforeinput fires before the value changes (when cancelable). input fires after the value has already changed. beforeinput does not fire on <select>; input can.
A common check is: window.InputEvent && typeof InputEvent.prototype.getTargetRanges === "function". That signals modern beforeinput / getTargetRanges support.
Did you know?

On contenteditable trees, the event target is the editing host—the nearest ancestor whose parent is not editable. Nested editable regions still bubble up to that host.

Next: beforematch

Learn the event that fires before hidden-until-found content is revealed.

beforematch →

About the author

Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful