Last active
September 4, 2017 17:54
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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