0

This question may be similar to

How to find the selection text beginning and end positions in Javascript?

But it is a little different.

I have a div like this-

<div class="text-block title">
   ve <i><u>ri</u> <b>t</i>us</b> anything anything hi hello bla bla
</div>

What I am trying to do is if a user selects this text like this-

enter image description here

Then I want to get the index of the selected text's starting and ending (for this condition 4,17).

Is there any way?

Thanks in advance for helping..

Community
  • 1
  • 1
Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161

2 Answers2

0

There is a way, but first add a "id" to your text please:

<div class="text-block title" id="text">
    ve <i><u>ri</u> <b>t</i>us</b> anything anything hi hello bla bla
</div>



$("#text").select(function(){       
    selectedText = document.getSelection();
    var index =  getIndex(selectedText , this.innerHTML );
    console.log("index: "+index.start+" , "+index.end;
});

//this function was writed by me, so...
var getIndex = function( wA ,wB){
    var a =  wA.length;
    var b = wB.length;
    var d = b-a;
    var that ={};
    if(a<=b){
        for(var i=0;i<=d;i++){
            var c = "";
            for(var j=0;j<wA.length;j++){
                c+=wB.charAt(j+i);
            }
            if(wA.toUpperCase()==c.toUpperCase()){
                that.start = i;
                that.end = i+j;
                return that;
            }
        }
    }
}

And thats all, check and try it, if u find errors tell me, thanks ;)

Alberto Acuña
  • 512
  • 3
  • 9
  • 28
0

It can be done much more simple! :)

$("textarea").select(function(e) {
 console.log(e.target.selectionStart);
  console.log(e.target.selectionEnd);
});

//fiddle: https://jsfiddle.net/Jorrex/upsopjqw/
textarea {
  height: 200px;
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
  Hi Hello Vi Veritas Vanitas Sora Roxas Rike Kairi Mickey Donald Goofy Ventus Aqua Terra Eraqus Xehanort
  
</textarea>
Jorrex
  • 1,503
  • 3
  • 13
  • 32