HTMLInputElement: selectionchange event
Baseline 2024Newly available
Since September 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Theselectionchange event of theSelection API is fired when the text selection within an<input> element is changed.This includes both changes in the selected range of characters, or if the caret moves.
This event is not cancelable.
The event is usually processed by adding an event listener on the<input>, and in the handler function read by theHTMLInputElementselectionStart,selectionEnd andselectionDirection properties.
It is also possible to add a listener on theonselectionchange event handler, and within the handler function useDocument.getSelection() to get theSelection. However this is not very useful for getting changes totext selections.
In this article
Syntax
Use the event name in methods likeaddEventListener(), or set an event handler property.
addEventListener("selectionchange", (event) => { })onselectionchange = (event) => { }Event type
A genericEvent.
Examples
The example below shows how to get the text selected in an<input> element.
HTML
<div> Enter and select text here:<br /><input rows="2" cols="20" /></div><div>selectionStart: <span></span></div><div>selectionEnd: <span></span></div><div>selectionDirection: <span></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
Specifications
| Specification |
|---|
| Selection API> # selectionchange-event> |
| Selection API> # dom-globaleventhandlers-onselectionchange> |