Limited availability
The selectionchange
event of the Selection 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 the HTMLInputElement
selectionStart
, selectionEnd
and selectionDirection
properties.
It is also possible to add a listener on the onselectionchange
event handler, and within the handler function use Document.getSelection()
to get the Selection
. However this is not very useful for getting changes to text selections.
Use the event name in methods like addEventListener()
, or set an event handler property.
addEventListener("selectionchange", (event) => { })
onselectionchange = (event) => { }
Event type
A generic Event
.
The example below shows how to get the text selected in an <input>
element.
<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 Specifications Browser compatibility
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3