Categories
JavaScript Answers

How to get caret position in HTML input with JavaScript?

Spread the love

Sometimes, we want to get caret position in HTML input with JavaScript

In this article, we’ll look at how to get caret position in HTML input with JavaScript.

How to get caret position in HTML input with JavaScript?

To get caret position in HTML input with JavaScript, we listen to the keydown event.

For instance, we write

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8" />

    <script type="text/javascript">
      window.addEventListener("load", () => {
        const [input] = document.getElementsByTagName("input");

        input.addEventListener("keydown", (e) => {
          console.log("Caret position: ", e.target.selectionStart);
        });
      });
    </script>

    <title>Test</title>
  </head>

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

to add an input in the body element.

Then we get the input in the load event listener with getElementsByTagName.

Then we call input.addEventListener with 'keydown' to listen to the keydown event which is emitted as we type.

And then we get the current caret position with e.target.selectionStart.

Conclusion

To get caret position in HTML input with JavaScript, we listen to the keydown event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *