Events

onselectionchange

Build a form with the HTML form generator

The document selection or a supported text-control selection changes. Event defined by a related web API or specification, not simply a portable HTML global handler. Use addEventListener on the actual target; inline handler exposure and browser support may differ. Event interface: Event. Propagation and cancellation depend on the target and event variant. Document events do not bubble; text-control events bubble. Use getSelection() for document text and selectionStart for inputs. Neither is cancelable. Example: Select text in the field or change its caret position. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.

Formal Syntax & Structure

html syntaxhtml
target.addEventListener("selectionchange", event => { /* handle event */ });

Parameters & Attributes

NameTypeDescription
eventEventEvent object delivered to the addEventListener callback; event.type is "selectionchange". Inspect target, currentTarget, bubbles and cancelable as appropriate.

Working Example

Example Snippethtml
<label for="demo">Sample text</label><input id="demo" value="Example text"><p role="status" id="log">Waiting for selectionchange</p><script>  const target = document.getElementById("demo");  const log = document.getElementById("log");  target.addEventListener("selectionchange", event => {    log.textContent = String(event.target.selectionStart + "–" + event.target.selectionEnd);  });</script>
HTML Reference