Home > Software engineering >  Why works with parragraf and not with textArea, (click over the word to get it)?
Why works with parragraf and not with textArea, (click over the word to get it)?

Time:02-13

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" >
  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?

CodePudding user response:

Try this solution:

<textarea id="wordcount" >
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>

  • Related