GlobalEventHandlers.onselectionchange
The onselectionchange
property of the GlobalEventHandlers
mixin is an event handler for selectionchange
events.
The Document.selectionchange_event
is fired when the Selection
of a Document
is changed. The Selection
consists of a starting position and (optionally) a range of HTML nodes from that position. Clicking or starting a selection outside of a text field will generally fire this event.
The HTMLTextAreaElement.selectionchange_event
and HTMLInputElement.selectionchange_event
events are fired, respectively, when the text selection within a <textarea>
or <input>
element is changed or the caret moves.
Syntax
document.onselectionchange = functionRef;
Value
functionRef
is a function name or a function expression. The function receives an Event
object as its sole argument.
Example
Getting the changed Document Selection
This code fragment shows how you can get selectionchange
events on the Document
. This will include events fired on text controls, which will bubble up to this handler.
document.onselectionchange = function() { console.log('New selection made'); let selection = document.getSelection(); };
For a full example, see our Key quote generator demo.
Using selectionchange with a text control
The example below shows how to get the start, end, and direction of text selected in a <textarea>
. It uses HTMLTextAreaElement
properties selectionStart
, selectionEnd
, and selectionDirection
(for an <input>
element you would use properties with the same name on HTMLInputElement
).
Note: We don't use Selection
here, because it contains information about selected Document
nodes, not the selected text.
HTML
<div>Enter and select text here:<br><textarea id="mytext" rows="2" cols="20"></textarea></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("mytext"); myinput.addEventListener("selectionchange", () => { document.getElementById("start").textContent = mytext.selectionStart; document.getElementById("end").textContent = mytext.selectionEnd; document.getElementById("direction").textContent = mytext.selectionDirection; });
Result
Specifications
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
onselectionchange |
11 |
12 |
52 |
5.5 |
15 |
5.1 |
≤37 |
18 |
52 |
14 |
5 |
1.0 |
See also
-
selectionchange
event - Related event handler:
GlobalEventHandlers.onselectstart
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onselectionchange