Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store information about a text selection on the browser

I'd like to highlight a range of text from an html page and get the highlighted position to then use to store comments.

My problem

I have an article page which allows the user to highlight a selection of text and add a comment. I have it to a point where I can position a UI box to the right of the selected text to enter a comment (think google docs).

I need to store information about the selected text so that I can link it to any comments. Ideally I would just store the selected text and then scan the content for that selection. This has a major flaw: what if two or more copies of the same text selection occur in the content.

The content itself is HTML stored in a DB.

For example a selection of the following paragraph has been highlighted (bold selection). I need to store information about the selection to be able to find it in the future:

"Efficiently revolutionize interoperable human capital via viral niches. Holisticly seize world-class potentialities through worldwide communities. Objectively embrace multidisciplinary niches for parallel paradigms. Professionally."

What I've done so far

Using the getBoundingClientRect() of the text selection range I can get the distance from the top of the page. Although useful for positioning the UI comment box I don't think this will help me to link comments to their selected text.

I can get the selected text from window.getSelection() but there could be multiple occurrences.

I'd like to NOT modify the content. i.e wrap the selection in a span or similar if I can help it as if a comment is removed it might be tricky to them remove the markup.

like image 615
iamjonesy Avatar asked May 25 '15 12:05

iamjonesy


1 Answers

window.getSelection gives you an object with much more than just the text. You could store the whole object, you'd have pretty much all the information you need. https://developer.mozilla.org/en-US/docs/Web/API/Selection

Normally anchorNode (on which you can apply parentNode to get the section in which the selection has begun) and startOffset should be unique for all your selections and you can target exactly the characters that have been selected without relying on text content.

like image 155
Julien Grégoire Avatar answered Oct 30 '22 01:10

Julien Grégoire