Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
How to get caret position word in textarea

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

https://jsfiddle.net/Prakashjsss/kerdh0tz/

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!