MDN self-hosted library · e01.org

HTMLInputElement: selectionchange event

Selection API

Selection API

The selectionchange event of the Selection API is fired when the text selection within an input element is changed in either extent or direction, whether the selection is a caret or a range of characters.

This event is not cancelable.

[!NOTE] When you change the selection programmatically, for example by calling setSelectionRange(), the selection updates immediately, but the selectionchange event is queued as a task. Its listeners run later, after the current script finishes executing. This contrasts with events such as focus and click, whose listeners run synchronously when triggered by focus() and click(), respectively.

Syntax

Use the event name in addEventListener():

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

Alternatively, assign to the event handler property of the interface:

onselectionchange = (event) => { }

Event type

A generic Event.

Examples

The example below shows how to get the text selected in an input element.

HTML

<div>
  Enter and select text here:<br /><input id="my-text" 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

const myInput = document.getElementById("my-text");

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

Result

Examples

Specifications

Browser compatibility