Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!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>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement