Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda