Getting selected text position Getting selected text position javascript javascript

Getting selected text position


s = window.getSelection();

Returns a Selection. So try

s = window.getSelection();oRange = s.getRangeAt(0); //get the text rangeoRect = oRange.getBoundingClientRect();

oRect will be the bounding rectangle in client (fixed) coordinates.


The easiest way is to insert a temporary marker element at the start or end of the selection and get its position. I've demonstrated how to do this before on Stack Overflow: How can I position an element next to user text selection?


Before using getBoundingClientRect, you need to know this note:

CSSOM working draft specifies that it returns a ClientRect for each border box

And by this 'standard':

For an inline element, the two definitions are the same. But for a block element, Mozilla will return only a single rectangle.

So if anyone reading this post wants a general solution for more precise positions and layouts of selected texts, I suggest the following approaches:

Option 1: Find exact starting and and ending point of texts by inserting invisible elements. Then calculate selected line rectangles with extracted computed line height and container width. APIs in use: window.getComputedStyle.

  • Pro: the result would be most precise for each line of text.
  • Con: 1) If the selection is across several nodes with different line heights and widths, the algorithm becomes complex. 2) And you need to implement the computation algorithm, which is too time consuming when implementing a simple feature.

Option 2: Wrap each text with a carefully styled inline element, extracting layout of each box, and merge results into lines.

  • Pro: Works for all continuous selections (that basically means all cases in current mainstream browser implementations.). Good enough precision for each line of texts.
  • Con: 1) Its result is a little inaccurate in some cases, as it adds error widths of kerning. 2) It's slow on very large selection of texts.

For option 2, rangeblock is an existing implementation with an easy API which gives you the absolution layout of each line of text:

let block = rangeblock.extractSelectedBlock(window, document);console.info("Text layout: " + JSON.stringify(block.dimensions));// output: Text layout: {Left: 100, Top: 90, Width: 200, Height: 50}