Skip to content

Instantly share code, notes, and snippets.

@verticalgrain
Last active September 4, 2017 17:54
Show Gist options
  • Select an option

  • Save verticalgrain/b06d97e95cd4f558fda69b748c3f6ef5 to your computer and use it in GitHub Desktop.

Select an option

Save verticalgrain/b06d97e95cd4f558fda69b748c3f6ef5 to your computer and use it in GitHub Desktop.
Insert text at the current caret position of the textarea field that currently has focus
// Usage:
// insertAtCaret('some text to insert');
(function ($, undefined) {
function insertAtCaret(text) {
var $focused = $(':focus');
var focusedCursorPosition = $focused.getCursorPosition();
var focusedContent = $focused.val();
var focusedNewContent = focusedContent.substr(0, focusedCursorPosition) + ' ' + string + focusedContent.substr(focusedCursorPosition);
$focused.val(focusedNewContent);
}
$.fn.getCursorPosition = function () {
var el = $(this).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment