Skip to Content
ohooks

useTextSelection

Tracks the user's current text selection, bounding rectangle, and ranges within the document or a target container.

Loading preview...

The useTextSelection hook listens to selectionchange, mouseup, keyup, scroll, and resize events to return the currently selected text string, Range objects, and bounding DOMRect—optionally scoped to a specific container element.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useTextSelection.json

Usage

Examples

Floating Popover Toolbar Over Selected Text

Scope selection tracking to an article container and position a floating action bar using rect.

Inspecting Selection Ranges

Access ranges and selection when you need to inspect or manipulate the underlying DOM Range objects.

API Reference

TextSelectionState

Selected text, ranges, and bounding rectangle returned by the hook.

Property
Specification
text
string
Currently selected plain text string.
rect
union
Bounding client rectangle of the primary selection range, or null when empty.
ranges
array
Cloned Range objects comprising the current selection.
selection
union
Underlying browser Selection object, or null when empty.