Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda