JavaScript Document selectionchange Event

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Document event
Baseline Widely available

What You’ll Learn

The Document selectionchange event fires when the document’s current Selection changes—selected text across DOM nodes, or a collapsed caret. Learn to listen on document, read document.getSelection(), and practice with five try-it labs.

01

Kind

Document event

02

Type

Event (generic)

03

Cancelable

No

04

Bubbles

No

05

Read

document.getSelection()

06

Status

Baseline · Widely available

Introduction

When you drag to highlight text on a page—or click so the caret moves—the browser updates the document Selection. Each time that happens, Document selectionchange fires.

The event object itself does not carry the new selection. Inside the handler, call document.getSelection() (or window.getSelection()) to read the current Selection object.

💡
Beginner tip

Document selectionchange is different from the selectionchange that fires on <input> / <textarea>. Those use character offsets (selectionStart / selectionEnd) and do bubble. Document selection uses DOM ranges and does not bubble.

Understanding Document selectionchange

A standard Document event that answers: “Did the page’s text selection (or caret) just change?”

  • Fires when the current Selection of a Document changes (MDN).
  • Includes creating/clearing a selection, moving range ends, replacing a range, or collapsing to a caret.
  • Not cancelable and does not bubble — listen on document.
  • Event type — a generic Event.
  • Handlerdocument.onselectionchange or addEventListener("selectionchange", ...).
  • Status — Baseline Widely available since March 2017 (MDN).

📝 Syntax

Use the event name with addEventListener, or set the handler property:

JavaScript
addEventListener("selectionchange", (event) => {});

onselectionchange = (event) => {};

Event type

A generic Event. Not cancelable and does not bubble.

MDN-style handlers

JavaScript
// addEventListener version
document.addEventListener("selectionchange", () => {
  console.log(document.getSelection());
});

// onselectionchange version
document.onselectionchange = () => {
  console.log(document.getSelection());
};

When it fires (MDN)

SituationBeginner meaning
Create or clear a selectionUser highlights text or deselects
Start/end boundary movesDrag handles / extend selection
Range changes completelySelection replaced as a whole
Collapsed caretSelection shrinks to a single caret position

⚖️ Document vs input selectionchange

TopicDocumentInput / textarea
What selection?DOM ranges across nodesOffsets inside the control’s value
How to readdocument.getSelection()selectionStart, selectionEnd, selectionDirection
Bubbles?No (fires on Document)Yes (fires on the control)
Handler propertyonselectionchange on documentAlso onselectionchange on the element
Typical usePage text highlight toolsCaret / highlight inside a form field

⚡ Quick Reference

GoalCode / note
Listendocument.addEventListener("selectionchange", fn)
Handler propertydocument.onselectionchange = fn
Current Selectiondocument.getSelection()
Selected textString(document.getSelection()) or .toString()
Collapsed caret?selection.isCollapsed
Range countselection.rangeCount
MDN statusBaseline Widely available (Mar 2017)

🔍 At a Glance

Four facts to remember about Document selectionchange.

Event type
Event

No selection payload

Means
Selection changed

Highlight or caret

Read with
getSelection()

Call inside the handler

Baseline
yes

Widely available

Examples Gallery

Examples follow MDN Document: selectionchange event. In try-it labs, select text on the page (not only inside an input) to fire the Document event, then inspect document.getSelection().

📚 Getting Started

Log the Selection object with both listener styles.

Example 1 — Log getSelection() (MDN)

Print the Selection whenever the document selection changes.

JavaScript
document.addEventListener("selectionchange", () => {
  console.log(document.getSelection());
});
Try It Yourself

How It Works

Matches MDN’s basic usage: the listener does not read properties from event—it asks the Document for the current Selection.

Example 2 — document.onselectionchange

Use the handler property and show whether anything is selected.

JavaScript
const out = document.getElementById("out");

document.onselectionchange = () => {
  const sel = document.getSelection();
  out.textContent = sel && sel.toString()
    ? "Selection active (" + sel.toString().length + " chars)"
    : "No text selected (caret or empty)";
};
Try It Yourself

How It Works

Prefer addEventListener for multiple listeners. The property form matches MDN’s onselectionchange syntax listing.

📈 Text, Caret & Preview

Read selected text, detect collapsed carets, and build a live preview.

Example 3 — Show Selected Text

Use Selection.toString() for the highlighted string.

JavaScript
const out = document.getElementById("out");

document.addEventListener("selectionchange", () => {
  const text = String(document.getSelection() || "");
  out.textContent = text
    ? 'Selected: "' + text + '"'
    : "(nothing selected)";
});
Try It Yourself

How It Works

Converting the Selection to a string is the simplest beginner-friendly way to get the highlighted text for toolbars, quotes, or share buttons.

Example 4 — Collapsed vs Range

Check isCollapsed and rangeCount.

JavaScript
const out = document.getElementById("out");

document.addEventListener("selectionchange", () => {
  const sel = document.getSelection();
  if (!sel) {
    out.textContent = "No Selection object";
    return;
  }
  out.textContent =
    "isCollapsed: " + sel.isCollapsed +
    " | rangeCount: " + sel.rangeCount +
    " | text length: " + sel.toString().length;
});
Try It Yourself

How It Works

A collapsed selection is usually a caret with no highlighted characters. A non-empty highlight sets isCollapsed to false.

Example 5 — Live Selection Preview

Update a sticky preview box as the user selects page text.

JavaScript
const preview = document.getElementById("preview");

document.addEventListener("selectionchange", () => {
  const text = String(document.getSelection() || "").trim();
  preview.textContent = text
    ? "You selected: " + text
    : "Select any text on this page…";
});
Try It Yourself

How It Works

Great for floating quote tools or “copy selection” UIs. Keep the work light—this event can fire often while the user drags.

🚀 Common Use Cases

  • Showing a floating toolbar when the user highlights text.
  • Building “quote this” or share-selection features.
  • Teaching how Document Selection differs from input caret APIs.
  • Logging selection analytics (lightly—the event fires frequently).
  • Syncing a live preview of the current highlight.

🔧 How It Works

1

User or script changes selection

Highlight text, clear it, move a range end, or place a caret.

Selection API
2

Document fires selectionchange

A generic Event arrives on document (no bubble).

event
3

You call getSelection()

Read the live Selection—the Event object does not store the details.

getSelection
4

Update your UI

Show selected text, enable a toolbar, or hide tools when collapsed.

📝 Notes

  • Baseline Widely available (since March 2017)—no Deprecated / Experimental / Non-standard banner.
  • Not cancelable and does not bubble—listen on document.
  • Always call document.getSelection() inside the handler for the current Selection.
  • Do not confuse with input/textarea selectionchange (different model; those bubble).
  • Related learning: visibilitychange, securitypolicyviolation, JavaScript hub.

Universal Browser Support

Document selectionchange is marked Baseline Widely available on MDN (since March 2017). Logos use the shared browser-image-sprite.png sprite from this project. Read the Selection with document.getSelection().

Baseline · Widely available

Document selectionchange

Fires when the Document Selection changes. Inspect the live Selection with document.getSelection().

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium Edge
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Legacy support in older IE; prefer modern browsers
Legacy
selectionchange Excellent

Bottom line: Listen on document for selectionchange, call getSelection() in the handler, and keep work light because the event fires often while dragging.

Conclusion

Document selectionchange is the Selection API signal that the page highlight or caret changed. Pair it with document.getSelection() to read the live Selection—the Event itself stays a simple notification.

Continue with visibilitychange, securitypolicyviolation, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Listen on document
  • Call document.getSelection() in the handler
  • Use toString() for highlighted text
  • Check isCollapsed before showing toolbars
  • Keep handler work cheap (event fires often)

❌ Don’t

  • Expect selection details on the Event object
  • Confuse Document selection with input selectionStart
  • Assume the event bubbles from an element
  • Run heavy work on every drag tick without throttling
  • Call this Experimental—it is Baseline Widely available

Key Takeaways

Knowledge Unlocked

Five things to remember about selectionchange

Selection changed — read it with document.getSelection().

5
Core concepts
🔍 02

Read separately

document.getSelection()

API
🔁 03

No bubble

Listen on document

DOM
✍️ 04

Not input API

Different from textarea

Compare
05

Baseline ready

Widely available

Status

❓ Frequently Asked Questions

What is the Document selectionchange event?

It fires when the current Selection of a Document changes—for example when the user highlights text, clears a selection, moves a range boundary, or collapses to a caret.

Is selectionchange deprecated or experimental?

No. MDN marks Document selectionchange as Baseline Widely available (since March 2017). It is not Deprecated, Experimental, or Non-standard.

Does selectionchange bubble?

No. MDN states the Document selectionchange event is not cancelable and does not bubble. Listen on document.

How do I read the selection?

Call document.getSelection() (or window.getSelection()) inside the handler. The Event object itself does not contain the updated selection details.

How is it different from input selectionchange?

Document selection uses DOM ranges via getSelection(). Input/textarea selection uses selectionStart/selectionEnd and that selectionchange event bubbles from the control.

Is there an onselectionchange property?

Yes. You can use document.onselectionchange or document.addEventListener("selectionchange", ...).

Did you know?

A document selection can represent either a range of selected content across DOM nodes or a collapsed caret position—both still go through selectionchange and getSelection().

Next: Document visibilitychange

Learn when the page becomes visible or hidden to the user.

visibilitychange →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful