Andy Matuschak
Andy Matuschak

Reputation: 183

How can I get the DOMRange-style offset within a DOM node for a given mouse (or document) location?

I know how to determine which DOM nodes intersect an absolute position. But say that's a text node. How can I determine the offset within the text node corresponding to that location? I'd like to construct a DOMRange from a known position to that position.

Upvotes: 4

Views: 325

Answers (1)

Chris Broadfoot
Chris Broadfoot

Reputation: 5112

The first step would be to find all Elements that intersect the position. You should use the Element.getBoundingClientRect method to do this. You can then easily get all of the Text nodes that sit within that Element. The hard part is to figure out what text within those Text nodes are within those bounds. You can start with the Element.getClientRects to get lines of text within that Element. Here's a great example.

You'll then want to construct a Range object, changing the startOffset and endOffset appropriately. You can use the getClientRects method on the Range object, too.

Upvotes: 1

Related Questions