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 = myinput.selectionStart;
  document.getElementById("end").textContent = myinput.selectionEnd;
  document.getElementById("direction").textContent = myinput.selectionDirection;
});

Result

Specifications

Specification
Selection API
# dom-globaleventhandlers-onselectionchange

Browser compatibility

BCD tables only load in the browser

See also