How to Get Cursor Position in JavaScript

How to Get Cursor Position in JavaScript

Ferenc Almasi β€’ Last updated 2021 September 18 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

If you ever had a specific case where you had to retrieve the position of a caret (your cursor's position) inside an HTML input field, you can do so using the selectionStart property of an input's value.

Copied to clipboard! Playground
<input type="text" id="input" value="123" />

<script>
  const input = document.getElementById('input');
  const position = input.selectionStart;
  
  // If the position of the cursor is at the very last character inside the input,
  // this will result in 3
  alert(position);
</script>
position.html

You can also outsource this functionality to the following one-line function, to reuse it across your application:

Copied to clipboard!
const getCaretPosition = e => e && e.selectionStart || -1;

getCaretPosition(document.getElementById('input')); // Returns 3
getCaretPosition(document.getElementById('email')); // Returns -1
getCaretPosition.js

Keep in mind that selectionStart can only be retrieved from the following list of input types:

  • text
  • password
  • search
  • tel
  • url
  • week
  • month
  • textarea

Therefore, in the example above, if you try to use it on an email type, it will always return -1.

How to Get Caret Position with JavaScript?
If you would like to see more Webtips, follow @flowforfrank

Resources

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.