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.
Code
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 —
documentwill 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.