selectionchange Tracks Input Selection Edges

The selectionchange event fires on the document for every caret move, so the active element decides whose selectionStart the toolbar should read.

TypescriptData Integrity

Code

typescriptsnippet
18 lines
const editor = document.querySelector('textarea') as HTMLTextAreaElement;
const formatBar = document.querySelector('.format-bar') as HTMLElement;

function syncToolbar(): void {
  const start = editor.selectionStart ?? 0;
  const end = editor.selectionEnd ?? 0;
  const selected = editor.value.slice(start, end);
  formatBar.classList.toggle('selection-active', end > start);
  console.log(end > start ? `selected ${selected.length} chars` : 'collapsed caret');
}

// selectionchange fires on the document for every caret or selection move,
// so the active element decides whose selection changed.
document.addEventListener('selectionchange', () => {
  if (document.activeElement === editor) syncToolbar();
});

syncToolbar();

From setup to output — selectionchange Tracks Input Selection Edges

The part that does the work is the function syncToolbar — everything else is wiring.

Points of care

  • Copy, run: the standard library answers every call in the file.
  • This is browser-side code — document will not resolve in Node.

Using it

The declaration doing the heavy lifting: function syncToolbar()

Key statements

document.addEventListener('selectionchange', () => {
  if (document.activeElement === editor) syncToolbar();
});
const start = editor.selectionStart ?? 0;
const end = editor.selectionEnd ?? 0;

Interactive Tools for This Topic

FAQ

Does selectionchange Tracks Input Selection Edges run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.