Zain Ul Abidin
Zain Ul Abidin

Reputation: 123

How to get single clicked word from textarea using JavaScript

Is it possible to get clicked word from textarea using jquery or javascript in IE and Firefox. Currently i'm using the below code and it's working perfectly fine in Chrome but it doesn't work at all in IE and Firefox.

<body>
<label for="result" style="display: none">Text</label>
<textarea id="result" rows="30" cols="100"></textarea>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>

    $("#result").click(function() {
        if($(this).val() !== null && $(this).val() !== ''){
            var selection = window.getSelection();
            selection.modify('extend', 'backward', 'word');
            var end = selection.toString();

            selection.modify('extend', 'forward', 'word');
            var start = selection.toString();
            selection.modify('move', 'forward', 'character');
            var wordInput = end+start;

            console.log(wordInput);
        }
    });
</script>
</body>

Expected Working

Let's suppose a textarea with text: 'Hello World'

When i click anywhere in 'Hello' it should print 'Hello' not the whole textarea value. Similarly for 'World' and so on.

Error in IE

SCRIPT438: Object doesn't support property or method 'modify'

Can anyone help me please? Thanks!

Upvotes: 2

Views: 1030

Answers (2)

Akhmedzianov Danilian
Akhmedzianov Danilian

Reputation: 947

No need to split all the text. This may lead to bad performance, because we do not know the length of text.

Give this a try:

function isSpace(character: string) {
  return /\s/.test(character);
}

export function getSelectedWord(
  selectionStart: number,
  value: string
): string | null {
  let start: number = selectionStart;
  let end: number = selectionStart;
  while (start - 1 >= 0 && !isSpace(value[start - 1]!)) {
    --start;
  }
  while (end + 1 < value.length && !isSpace(value[end + 1]!)) {
    ++end;
  }
  const word = value.slice(start, end + 1);
  return word || null;
}

Upvotes: 0

Ufuk
Ufuk

Reputation: 448

This code could help you, i guess.

const getTheWord = (selectionStart, value) => {
  let arr = value.split(" ");
  let sum = 0
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i].length + 1
    if (sum > selectionStart) return arr[i]

  }
}

const myArea = document.getElementById("myArea")
myArea.value = "Hello world!"
myArea.onclick = (e) => {
let i = e.currentTarget.selectionStart
console.log(getTheWord(i, myArea.value))
}
<textarea id="myArea"></textarea>

Upvotes: 3

Related Questions