-
Notifications
You must be signed in to change notification settings - Fork 22.4k
/
index.md
73 lines (49 loc) · 2.19 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
---
title: "HTMLInputElement: selectionchange event"
short-title: selectionchange
slug: Web/API/HTMLInputElement/selectionchange_event
page-type: web-api-event
status:
- experimental
browser-compat: api.HTMLInputElement.selectionchange_event
---
{{APIRef}}{{SeeCompatTable}}
The **`selectionchange`** event of the [Selection API](/en-US/docs/Web/API/Selection) is fired when the text selection within an {{HTMLElement("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 {{HTMLElement("input")}}, and in the handler function read by the {{domxref("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 {{domxref("Document.getSelection()")}} to get the {{domxref("Selection", "Selection")}}. However this is not very useful for getting changes to _text_ selections.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("selectionchange", (event) => {});
onselectionchange = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
The example below shows how to get the text selected in an {{HTMLElement("input")}} element.
### HTML
```html
<div>
Enter and select text here:<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;
});
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}