The browser fires the selectionchange event of the Selection API when the current Selection of a Document changes. A document selection represents either a range of selected content across DOM nodes or a collapsed caret position.
This event is not cancelable and does not bubble.
Use the event name in methods like addEventListener(), or set an event handler property.
addEventListener("selectionchange", (event) => {})
onselectionchange = (event) => {}A generic Event.
The Document object selectionchange event is fired when:
The event object itself does not contain the updated selection details. You can retrieve the current selection by calling document.getSelection() within your event listener.
This event differs significantly from the selectionchange event fired on <input> and <textarea> text controls:
Document.getSelection() for inspection. Text inputs maintain independent selections within their internal text values, using character offsets inspected via selectionStart, selectionEnd, and selectionDirection.selectionchange event fires directly on the Document and does not bubble. The text input selectionchange event fires on the input/textarea element and bubbles up the DOM tree.See the selectionchange event of HTMLInputElement and the selectionchange event of HTMLTextAreaElement for more details of the text input events.
// addEventListener version
document.addEventListener("selectionchange", () => {
console.log(document.getSelection());
});
// onselectionchange version
document.onselectionchange = () => {
console.log(document.getSelection());
};