EditContext: textupdate イベント

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Experimental: これは実験的な機能です。
本番で使用する前にブラウザー互換性一覧表をチェックしてください。

EditContext インターフェイスの textupdate イベントは、ユーザーが EditContext のインスタンスに関連付けられた編集可能な領域のテキストまたは選択範囲を変更した時発火します。

このイベントにより、ユーザーの入力に応じて UI 内に新しいテキストや選択範囲を描画できます。

構文

addEventListener() などのメソッドでイベント名を用いるか、イベントハンドラープロパティを設定します。

js
addEventListener("textupdate", (event) => {});

ontextupdate = (event) => {};

イベント型

TextUpdateEvent です。Event を継承しています。

イベントプロパティ

以下に挙げるプロパティに加え、親の Event インターフェイス由来のプロパティも使用可能です。

TextUpdateEvent.updateRangeStart 読取専用

更新されたテキストの範囲の始点の文字の添字を返します。

TextUpdateEvent.updateRangeEnd 読取専用

更新されたテキストの範囲の終点の文字の添字を返します。

TextUpdateEvent.text 読取専用

更新された範囲に挿入されたテキストを返します。

TextUpdateEvent.selectionStart 読取専用

更新後の新しい選択範囲の始点の文字の添字を返します。

TextUpdateEvent.selectionEnd 読取専用

更新後の新しい選択範囲の終点の文字の添字を返します。

textupdate で更新されたテキストを描画する

以下の例では、EditContext API の textupdate イベントを用いて、ユーザーが編集可能な <canvas> 要素に入力したテキストを描画します。

html
<canvas id="editor-canvas"></canvas>
js
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
const editContext = new EditContext();
canvas.editContext = editContext;

editContext.addEventListener("textupdate", (e) => {
  // <canvas> にフォーカスがある状態でユーザーがテキストを入力すると、
  // このイベントが発火します。これをテキストの再描画に用います。
  console.log(
    `The user entered the text: ${e.text} at ${e.updateRangeStart}. Re-rendering the full EditContext text`,
  );
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillText(editContext.text, 10, 10);
});

仕様書

Specification
EditContext API
# dom-editcontext-ontextupdate

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
textupdate event
Experimental

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Experimental. Expect behavior to change in the future.