Skip to content

Instantly share code, notes, and snippets.

@memandip
Last active July 8, 2019 06:48
Show Gist options
  • Save memandip/76bf7be51d8a545e13cfdf5b9c25f6b9 to your computer and use it in GitHub Desktop.
Save memandip/76bf7be51d8a545e13cfdf5b9c25f6b9 to your computer and use it in GitHub Desktop.
Get nearest word of the cursor position in textbox
<!DOCTYPE html>
<html lang="en">
<head>
<title>Get Nearest word of cursor</title>
</head>
<body>
<input id="textArea" type="text"/>
<br />
<input id="Submit" type="submit" value="Test" onclick="getPreviousWordOfCursor()"/>
<script>
function getPreviousWordOfCursor() {
var textElement = document.getElementById('textArea')
let caretPos = 0
if (document.selection) {
textElement.focus()
let Sel = document.selection.createRange()
Sel.moveStart('character', -textElement.value.length)
caretPos = Sel.text.length
} else if (textElement.selectionStart || textElement.selectionStart == '0') {
caretPos = textElement.selectionStart
}
let text = textElement.value
let preText = text.substring(0, caretPos)
let resultWord
if (preText.indexOf(" ") > 0) {
let words = preText.split(" ")
resultWord = words[words.length - 1]
}
else {
resultWord = preText
}
alert(resultWord)
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment