JSFiddle - React, Tailwind, and code Playground

by apoucoz

HTML

<textarea id="the_id_value">Здесь может быть любой ваш текст</textarea>

<a href="#" onclick="$('#the_id_value').getCursorPosition('~Бла бла~');return false;">Вставь текст на позицию курсора</a>

CSS

textarea {
  width: 100%;
}

JavaScript

var apofpos;

(function($, undefined) {  
    $.fn.getCursorPosition = function(s) {  
        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;  
        }
        apofpos = pos;
        aposetdatatofield($(this), s);
    }
})(jQuery);

$.fn.setCursorPosition = function(pos) {
  this.each(function(index, elem) {
    if (elem.setSelectionRange) {
      elem.setSelectionRange(pos, pos);
    } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  });
  return this;
};

function aposetdatatofield(a, b) {
	a.val(a.val().substr(0, apofpos) + b + a.val().substr(apofpos, a.val().length)).setCursorPosition(apofpos+b.length).focus();
}