0

i want to get the word clicked and why work with paragraf and not with textArea from html?

document.getElementById("wordcount").addEventListener('click', (e) => {
  s = window.getSelection();
  var range = s.getRangeAt(0);
  var node = s.anchorNode;

  while (range.toString().indexOf(' ') != 0) {
    range.setStart(node, (range.startOffset - 1));
  }
  range.setStart(node, range.startOffset + 1);

  do {
    range.setEnd(node, range.endOffset + 1);

  } while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');

  var str = range.toString().trim();
  alert(str);
});
<textArea id="wordcount" class="clickable">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum ante nunc.
</textArea>

here works with <p> but i want to use with textArea

Detect which word has been clicked on within a text what is the problem?

signup
  • 135
  • 1
  • 16

1 Answers1

1

Try this solution:

<textarea id="wordcount" class="clickable">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum ante nunc.
</textarea>

<script>
    const textarea = document.getElementById('wordcount');

    const grabWord = (start, val) => {
        let arr = val.split(' ');
        let sum = 0;
        for (let index in arr) {
            sum += arr[index].length + 1;
            if (sum > start) return arr[index];
        }
    };

    const getClickedWord = (e) => {
        let start = e.currentTarget.selectionStart;
        console.log(grabWord(start, textarea.value));
    };

    textarea.addEventListener('click', getClickedWord);
</script>
mstephen19
  • 1,733
  • 1
  • 5
  • 20