JavaScript Get & Set Cursor Position in Textarea

The Caret is a lightweight jQuery plugin that makes it easy to get & set cursor position with JavaScript in textarea. You can easily get current position of cursor and store it in JavaScript variable. Similarly, you can also set desired cursor position with the help of this plugin.

Moreover, the plugin also support editable div to get and set cursor position.

Plugin Overview

Plugin: Caret
Author: Gideon Sireling
Licence: BSD-3-Clause
Published: August 21, 2019
Repository: Fork on GitHub
Dependencies: jQuery 1.3.1 or Latest version
File Type: zip archive (HTML, CSS & JavaScript )
Package Size: 4.19 KB

NPM Package Installation:

npm i @accursoft/jquery-caret

How to Get & Set Cursor Position in Textarea

1. To getting started using Caret plugin to get textarea cursor position in JavaScript, load the jQuery and plugin JavaScript file into your HTML document.

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<!-- Caret JS -->
<script src="js/jquery.caret.js"></script>

2. After that, create HTML textarea element with a unique id.

<textarea id="text"> Some sample text in textarea... </textarea>

3. To get the cursor position, call the plugin with your textarea selector.

var cursor_position = $('#text').caret();
console.log("Cursor position is: "+cursor_position);

4. To set the cursor position use the following syntax.

Pass the value of your desired position in number.

$('#text').caret(4);

5. The following syntax set the cursor position to the end.

$('#text').caret(-1);