Insert Text At the Cursor Position With insertAtCaret Plugin

File Size: 15.8 KB
Views Total: 211
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Insert Text At the Cursor Position With insertAtCaret Plugin

insertAtCaret is a lightweight (~1.45kb) jQuery plugin that gives you the ability to insert any text in a text field at the current caret (cursor) position. 

Works with input fields, textareas and any contenteditable DOM element. Easy to implement and use, requiring only one line of JS code to perform the text insertion operation.

See Also:

How to use it:

1. Download the plugin and insert the jquery.insert-at-caret.min.js script after jQuery.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/jquery.insert-at-caret.min.js"></script>

2. Call the insertAtCaret() method, passing the text you want to insert and the target element.

<h4>Input Field</h4>
<input value="Example" />

<h4>Textarea</h4>
<textarea class="form-control"></textarea>

<h4>contenteditable</h4>
<div id="demo" contenteditable>Example</div>
// Input Field
$('input').insertAtCaret('jQueryScript');

// Textarea
$('textarea').insertAtCaret('jQueryScript');

// contenteditable
$('#demo').insertAtCaret('jQueryScript');

Changelog:

2023-06-20

  • Updated jQuery dependency. Now it requires at least 3.5.0 version.

2023-06-19

  • fix: added focus to contentEditabl element

This awesome jQuery plugin is developed by emreerkan. For more Advanced Usages, please check the demo page or visit the official website.