Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pinpoint a word or a selection in the entire document?

I am trying to highlight a part of the text on my website. This highlighted text will be saved for the specific user in a database and when the document is opened again it will show the previously highlighted text. I assumed I would be using javascript to highlight the text but I cannot seem to find a way to pinpoint where the word is that I am highlighting.

function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
            }
    else return "";
    return txt;
}

I am using that to get the selection but I cannot figure out where the selection is in the text. The biggest annoyance is when I have duplicates within the line or text so if I were to use search then I would find the first instance and not the one I was looking for.

So the question is : How do you pinpoint a word or a selection in the entire document?

like image 430
vman Avatar asked Mar 07 '11 02:03

vman


People also ask

How do you select an entire document in word?

Select text by using the keyboard. Note: To select an entire document, press CTRL+A.

What tool allows you to find a specific word?

Hold the Ctrl keyboard key and press the F keyboard key (Ctrl+F) or right-click (click the right mouse button) somewhere on the article and select Find (in this article). This will bring up a text box to type search words into (see picture below).


1 Answers

You can use my Rangy library and its selection serialization module for this. Rangy's core provides a consistent Selection and Range API for all browsers and the serializer module builds on this by converting each selection boundary into a path through the document. See the linked documentation for more details.

like image 152
Tim Down Avatar answered Oct 22 '22 17:10

Tim Down