The HTML onselectionchange event
The HTML onselectionchange attribute runs JavaScript when the text selection in the document (or an editable field) changes. It is an inline handler for the selectionchange event; in modern code prefer addEventListener('selectionchange', …).
Overview
The onselectionchange event attribute runs JavaScript when the selection changes. In JavaScript the event itself is named selectionchange. Drop the on prefix when you call addEventListener.
It is a document-level event rather than one tied to a particular element, so it is handled on document, which fires it whenever the user's text selection changes.
You can wire this up with the inline onselectionchange HTML attribute, but the modern, recommended approach is document.addEventListener('selectionchange', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<body onselectionchange="handler()">…</body>
document.addEventListener('selectionchange', handler);
Best practices
- Prefer
document.addEventListener('selectionchange', handler)over the inlineonselectionchangeattribute; it separates behavior from markup and allows multiple handlers. - Attach these on
windowwithaddEventListenerrather than as <body> attributes. - Keep these handlers fast; they run at moments that affect the whole page.
- Remove listeners you no longer need to avoid leaks in long-lived pages.
Frequently asked questions
What is the onselectionchange event?
selectionchange.Where do I attach this event?
document, which fires it whenever the user's text selection changes.Can I use it as a body attribute?
document, which sits above <body>, so a handler there never sees it. It is fired at a focused <input> or <textarea> and does bubble, so a body handler would catch only those. Attach it with document.addEventListener('selectionchange', handler) to catch every case.Should I use the onselectionchange attribute or addEventListener?
document.addEventListener('selectionchange', …) in JavaScript. The inline onselectionchange attribute works but mixes behavior into the markup and allows only one handler per element.