JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="myarea" cols="40" rows="10">
Try tab here ->
and here ->
and here ->
</textarea>
JavaScript
$('#myarea').on('keydown', function(e) {
var thecode = e.keyCode || e.which;
if (thecode == 9) {
e.preventDefault(); // prevent default
var html = $('#myarea').val();
var pos = $('#myarea').getCursorPosition(); // get cursor position
var prepend = html.substring(0,pos); // substring to current position for first half of text
var append = html.replace(prepend,''); // remove prepended text to get 2nd half of text
var newVal = prepend+' '+append; // add 4 spaces in the middle
$('#myarea').val(newVal); // update new val
$('#myarea').setCursorPosition(pos+4); // set cursor position
}
});
new function($) {
$.fn.getCursorPosition = function() {
var pos = 0;
var el = $(this).get(0);
// IE Support
if (document.selection) {
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;
}
// Firefox support
else if (el.selectionStart || el.selectionStart == '0')
pos = el.selectionStart;
return pos;
}
} (jQuery);
new function($) {
$.fn.setCursorPosition = function(pos) {
if ($(this).get(0).setSelectionRange) {
$(this).get(0).setSelectionRange(pos, pos);
} else if ($(this).get(0).createTextRange) {
var range = $(this).get(0).createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
}(jQuery);