I am trying to get the position of the selected text, replace it with some HTML and then I want to persist the position of the selected text, so that the next time I render the html I want to show the highlight on the selected text
I have some content displayed inside a Div
Now I select the text "scrambled section of De finibus" which is in line 2 and from some offset from the start. I replace this text with the span around the text like :
function textSelection() {
var sel = window.getSelection();
var range = sel.getRangeAt(0).cloneRange();
var markerTextChar = range.extractContents();
var markerEl, markerId = "sel_" + new Date().getTime() + "_" + Math.random().toString().substr(2);
markerEl = document.createElement("span");
markerEl.id = markerId;
markerEl.appendChild(markerTextChar);
range.insertNode(markerEl);
markerEl.style.backgroundColor = ' rgba(246,195,66,0.3)';
markerEl.style.cursor = 'pointer';
}
<div id='page-view' onmouseup='textSelection()'> In publishing and graphic design, lorem ipsum is a filler text or greeking commonly used to demonstrate the textual elements of a graphic document or visual presentation. Replacing meaningful content with placeholder text allows designers to design the
form of the content before the content itself has been produced. The lorem ipsum text is typically a scrambled section of De finibus bonorum et malorum, a 1st-century BC Latin text by Cicero, with words altered, added, and removed to make it nonsensical,
improper Latin.
</div>
Now I add styles to this span to highlight the selection. Now what I want to do is to save this position so that the next time the html page is displayed, I want to highlight the same selection. Note that, there might be repetition of the same selected text in some other location, so I don't want to inadvertently highlight the wrong position.
- Is there a way I can achieve this?
- The text containing Div does not have the property 'contenteditable'
- So far what I have is getting the 'clientRects' of the selected text and creating a div and adding style to that div and appending to the body, but I don't want to do that
- The HTML for the actual text is generated in the backend using Markup language parser like MarkDown
Edit :
Let me add more details. Like a github wiki , I am displaying the contents of the wiki by parsing the contents and generating the html based on the selected language mode like Markdown/Textile. I want a way to somehow map the selected text to the actual text line number when the page is edited. When the page edit is clicked the contents are shown using codemirror code editor.
Thanks