Search code examples
javascriptjquerystringposition

Onclick anywhere on word get position number of word inside textarea - JQuery


this is my code. It works only when I click on the first letter of any word. Then it gives me the position of that word like 0 for first word, 1 for second and etc. But when when I click on middle or anywhere then It don't take position number until I don't click on the start of first letter. Here's how my code is running:

$("#checktext").on('click', function(e) {
         var text = document.getElementById("checktext").value,
        element = $("#checktext")[0],
        arr1 = text.split(" "),
        length = 0,
        selectIndex = element.selectionStart;
         if (selectIndex == 0) {
        console.log(arr1.indexOf(arr1[0]));
         } else {
        for (var i = 0; i < arr1.length; i++) {
             length = length + arr1[i].length + 1;
             if (length == selectIndex) {
            console.log(i + 1);
            break;
             }
        }
        }
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
</script>
<textarea id="checktext">This will only work if click on start of each letter.</textarea>


Solution

  • The Problem is in your condition:

    length == selectIndex
    

    This is only true for the first letter of every word. But you want it to be true for the range of letters for every word:

    selectIndex >= startOfWord && selectIndex <= endIndexOfWord
    

    $("#checktext").on('click', function(e) {
      var text = document.getElementById("checktext").value,
        element = $("#checktext")[0],
        arr1 = text.split(" "),
        length = 0,
        selectIndex = element.selectionStart;
      for (var i = 0; i < arr1.length; i++) {
        let start = length; // start index of the next word to check
        length = length + arr1[i].length; // end index of your next word to check
        if (selectIndex >= start && selectIndex <= length) {
          console.log("Selected Index: " + i);
          break;
        }
        length++; // add the whitespace after the check
      }
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <textarea id="checktext">This will only work if click on start of each letter.</textarea>

    Also: you probably should use a different variable name instead of length. It is not the length but the end index of your word. I guess thats a part why this error occured, you expect that variable to be something different than it is.