i am new in javascript, trying to get the word at caret position from textarea. I have a following code which works fine for <div contenteditable="true"></div>
As soon i try to implement it with textarea it wont run
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function getCursorWord() {
var capture, word = "";
if (window.getSelection && (capture = window.getSelection()).modify) {
var selectedRange = capture.getRangeAt(0);
capture.collapseToStart();
capture.modify("move", "backward", "word");
capture.modify("extend", "forward", "word");
word = capture.toString();
// Restore selection
capture.removeAllRanges();
capture.addRange(selectedRange);
} else if ((capture = document.selection) && capture.type != "Control") {
var range = capture.createRange();
range.collapse(true);
range.expand("word");
word = range.text;
}
console.log(word);
}
</script>
</head>
<body>
<div contenteditable="true" onkeyup="getCursorWord()" style="padding: 10px; background: #f2f4fa; outline: none"></div>
</body>
</html>
Will anybody help put on right direction, to make code run with textarea. Any help will be appreciated
Here is the fiddle