HTMLInputElement: selectionchange イベント

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

selectionchange選択 API のイベントで、 <input> 要素の中でテキストの選択状態が変化したときに発行されます。 これは、文字単位の選択範囲位が変化した場合も、キャレットが移動したときも含みます。

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

このイベントは通常 <input> 上にイベントリスナーを追加し、ハンドラー関数内で HTMLInputElementselectionStartselectionEndselectionDirection の各プロパティを読み取ることで処理します。

また、onselectionchange イベントハンドラーにリスナーを追加し、ハンドラー関数内で Document.getSelection() を使って選択状態を得ることもできます。しかし、これはテキストの選択範囲の変更を取得するのにはあまり便利ではありません。

構文

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

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

onselectionchange = (event) => {};

イベント型

一般的な Event です。

以下の例は、 <input> 要素の中にあるテキストの選択状態を取得する方法を示しています。

HTML

html
<div>
  こちらにテキストを入力して選択してください:<br /><input
    id="mytext"
    rows="2"
    cols="20" />
</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.