1

I am trying to include functionality that will enable a user to highlight text and have that text returned. I would also like to return the location of that text within #textcontainer div.

My issue: if the user highlights the second 'and' in the text below, position will equal the indexOf the first 'and' in the div instead of the second. How do I change this to have position return the position of the second 'and' (the one that is highlighted)?

    <div id = 'textcontainer'>
        and second third and
    </div>


     // beginning of highlight js
    $('#highlight').click(function (e) {
        e.preventDefault();

        // get highlighted text
        var selection = window.getSelection();
        var txt = selection.toString();
        console.log(txt);

        fulltext = $("#textcontainer").text();
        console.log(fulltext);

        position = fulltext.indexOf(txt);
        console.log(position);

    })
  // end of highlight js
sharataka
  • 5,014
  • 20
  • 65
  • 125
  • 2
    Have you looked into [Selection#getRangeAt](https://developer.mozilla.org/en-US/docs/DOM/Selection/getRangeAt) and the position properties of [Range](https://developer.mozilla.org/en-US/docs/DOM/range)? – Jeremy Roman May 06 '13 at 13:12
  • could put the words in an array and search the array for the second occurrence. probably better would be to get the index of the first occurrence, then split the string at the end of that word (so, the index + word.length) and search the remaining part of the string. could also use a regular expression match. – user428517 May 06 '13 at 13:14
  • @JeremyRoman what about for IE support? The answer below mentions that getRange doesn't work for IE. Anything in jQuery that I could use for cross-browser usage? – sharataka May 06 '13 at 13:22

1 Answers1

2

You're in luck, since window.getSelection() returns a Selection object, which in turn has a getRangeAt method, which you can use like so:

var selection = window.getSelection();
var range = selection.getRangeAt(0);

var start = range.startOffset, end = range.endOffset;

Edit: Note that IE has a completely different selection API. For cross-browser compatibility, you may want to take a look at Rangy (note: I don't have any experience with the library).

Edit 2: See this answer for some jQuery plugins.

Community
  • 1
  • 1
Linus Thiel
  • 38,647
  • 9
  • 109
  • 104