2

I am building a JS script and I want to get the position of a word in a text by clicking on it. For example:

This is my paragraph and I want to get the word paragraph of this text.

Let's assume that I am clicking on the paragraph that appears for second time in this text. The result should be 12 as it's the 12th word. How could I do that?

So far I can double click on a word and get it but I also need its position.

 <script> $(document).ready(function() {

        var p = $('p');
        p.css({ cursor: 'pointer' });

        p.dblclick(function(e) {
            var range = window.getSelection() || document.getSelection() || document.selection.createRange();
            var word = $.trim(range.toString());
            if(word != '') {
                alert(word);
            }
            range.collapse();
            e.stopPropagation();
        });

    });</script>

    <p>This is my paragraph and I want to get the word paragraph of this text.</p>
orestiskim
  • 81
  • 4
  • 9
  • I don't think it is possible. The nearest similar job would be done by [highlighting](https://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text). When you click the `

    `, you get the tag element in the whole, not its content, so is not possible.

    – RompePC Jun 20 '17 at 12:52

4 Answers4

2

What do you think about this?

var p = $('#text');
var text = p.html();

// wrap each word into custom tag with data-i attribute as index
p.html(text.split(' ').map(function(word,index){

  return `<w-d data-i='${index+1}'>${word}</w-d>`

}).join(' '))

// bind actions
$('w-d').click(function(){

  var index = $(this).attr('data-i');
  alert(index)
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="text">Click on my words.</p>
Jan Ciołek
  • 1,796
  • 3
  • 17
  • 32
2

You can use anchorOffset to determine the index of the first character of your selection (thanks @tech2017).

After that, it's a matter of counting how many words come before this index.

The easiest way to count words, is counting the whitespace instead. We'll split on \s+ to make sure we account for multiple spaces, newlines and more.

Note: I do not know how well this works in all browsers. Make sure to test!

$(document).ready(function() {

  var p = $('p');
  p.css({
    cursor: 'pointer'
  });

  p.dblclick(function(e) {
    var range = window.getSelection() || document.getSelection() || document.selection.createRange();
    var word = $.trim(range.toString());
    if (word != '') {
      // Count words
      var charIdx = range.anchorOffset;
      var countStr = range.anchorNode.textContent.substr(0, charIdx);
      var wordNumber = (countStr === "") ? 1 : countStr.trim().split(/\s+/).length + 1;
      alert(wordNumber);
    }
    //range.collapse();
    e.stopPropagation();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is my paragraph and I want to get the word paragraph of this text.</p>
Kokos
  • 9,051
  • 5
  • 27
  • 44
  • 1
    Two observations: 1) Both **This** and **is** are denoted with index 1, and 2) the period at the end of the sentence has it's own index, 15. – chazsolo Jun 20 '17 at 13:44
  • Concering the dot, interesting observation. Depends on what the OP wants but you could remove all non-alphanumerical and non-whitespace characters pre-counting. – Kokos Jun 20 '17 at 13:48
  • I think it that is the most efficient way to do it. Thanks @Kokos – orestiskim Jun 23 '17 at 01:58
0

You can use anchorOffset to get the position of the selected text (index 0 based). Check this fiddle:

https://jsfiddle.net/o2gxgz9r/8945/

$(document).ready(function() {

  var p = $('p');
  p.css({
    cursor: 'pointer'
  });

  p.dblclick(function(e) {
    var range = window.getSelection() || document.getSelection() || document.selection.createRange();
    var word = $.trim(range.toString());
    if (word != '') {
      alert(word);
      var temp = range.anchorOffset;
      alert(temp);
    }
    //range.collapse();
    e.stopPropagation();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is my paragraph and I want to get the word paragraph of this text.</p>
tech2017
  • 1,806
  • 1
  • 13
  • 15
  • That's pretty close but not what exaclty I am looking for, because it is counting characters instead of words – orestiskim Jun 20 '17 at 13:09
-2

You have to count the Whitespace character and then add 1 to the result.

Example: This1is2my3paragraph4and5I6want7to8get9the10word11paragraph of this text.

Hakim
  • 1