tom joy
tom joy

Reputation: 411

Javascript find occurance position of selected text in a div

I have a string with a word five times.if i selected forth hello it should return 4

 <div id="content">hello hai hello hello hello</div>

getting selected text script

<script>
 if(window.getSelection){
   t = window.getSelection();
 }else if(document.getSelection){
   t = document.getSelection();
 }else if(document.selection){
   t =document.selection.createRange().text;
 }
 </script>

If am selecting hai it should return 1.

If am selecting hello hai it should return 1. please help.

Upvotes: 3

Views: 8168

Answers (2)

Tim Down
Tim Down

Reputation: 324547

Assuming that the contents of the <div> are guaranteed to be a single text node, this is not too hard. The following does not work in IE < 9, which does not support Selection and Range APIs. If you need support for these browsers, I can provide code for this particular case, or you could use my Rangy library.

Live demo: http://jsfiddle.net/timdown/VxTfu/

Code:

if (window.getSelection) {
    var sel = window.getSelection();
    var div = document.getElementById("content");

    if (sel.rangeCount) {
        // Get the selected range
        var range = sel.getRangeAt(0);

        // Check that the selection is wholly contained within the div text
        if (range.commonAncestorContainer == div.firstChild) {
            // Create a range that spans the content from the start of the div
            // to the start of the selection
            var precedingRange = document.createRange();
            precedingRange.setStartBefore(div.firstChild);
            precedingRange.setEnd(range.startContainer, range.startOffset);

            // Get the text preceding the selection and do a crude estimate
            // of the number of words by splitting on white space
            var textPrecedingSelection = precedingRange.toString();
            var wordIndex = textPrecedingSelection.split(/\s+/).length;
            alert("Word index: " + wordIndex);
        }
    }
}

Upvotes: 9

davidethell
davidethell

Reputation: 12018

You'll need to use the Range capabilities of the DOM. Here is how to get the currently selected range:

var currentRange = window.getSelection().getRangeAt(0);

From there currentRage.startOffset will tell you the position of your selection within the file. So you'll need to compare that with the start range of your element:

var myContent = document.getElementById('content');
var divRange = document.createRange ();
divRange.selectNodeContents (myContent);

Now you can compare the divRange.startOffset with your selection startOffset and determine which one you're on.

Upvotes: 3

Related Questions