Skip to content
Advertisement

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!

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement