Get caret position in HTML input?

user345824 picture user345824 · Feb 8, 2011 · Viewed 92.9k times · Source

How do I get the index of the text caret in an input?

Answer

Caio picture Caio · Feb 8, 2011

-> selectionStart

<!doctype html>
    
<html>
  <head>
    <meta charset = "utf-8">

    <script type = "text/javascript">
      window.addEventListener ("load", function () {
        var input = document.getElementsByTagName ("input");
        
        input[0].addEventListener ("keydown", function () {
          alert ("Caret position: " + this.selectionStart);
          
          // You can also set the caret: this.selectionStart = 2;
        });
      });
    </script>
    
    <title>Test</title>
  </head>

  <body>
    <input type = "text">
  </body>
</html>