HTMLTextAreaElement: selectionchange イベント

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

selectionchange選択 API のイベントで、<textarea> 要素内のテキストの選択状態が変更されたときに発生します。 これは、文字の選択範囲の変更と、キャレットが移動した場合の両方を含みます。

このイベントはキャンセル不可です。

イベントは通常 <textarea> にイベントリスナーを追加することで処理され、HTMLTextAreaElement で読み込まれるハンドラー関数で処理されます。selectionStartselectionEndselectionDirection プロパティで読み取ります。

グローバルな onselectionchange イベントハンドラーにリスナーを追加し、ハンドラー関数内で Document.getSelection() を使用して Selection を取得することも可能です。しかし、これは テキスト の選択範囲の変更を取得するのにはあまり有益ではありません。

構文

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

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

onselectionchange = (event) => {};

イベント型

一般的な Event です。

下記の例では、<textarea> 要素内での選択範囲を取得する方法を紹介します。

HTML

html
<div>
  ここにテキストを入力して選択してください:<br /><textarea
    id="mytext"
    rows="2"
    cols="20"></textarea>
</div>
<div>selectionStart: <span id="start"></span></div>
<div>selectionEnd: <span id="end"></span></div>
<div>selectionDirection: <span id="direction"></span></div>

JavaScript

js
const myinput = document.getElementById("mytext");

myinput.addEventListener("selectionchange", () => {
  document.getElementById("start").textContent = myinput.selectionStart;
  document.getElementById("end").textContent = myinput.selectionEnd;
  document.getElementById("direction").textContent = myinput.selectionDirection;
});

仕様書

Specification
Selection API
# selectionchange-event
Selection API
# dom-globaleventhandlers-onselectionchange

ブラウザーの互換性

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
selectionchange 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.
See implementation notes.