-1

HTML:

<textarea id="text"></textarea>

JavaScript:

document.querySelector('#text').addEventListener('keydown', e => {
  if (e.keyCode == 9) e.preventDefault();
});

Are you able to still write a tab without unfocusing the textarea?

johannchopin
  • 13,720
  • 10
  • 55
  • 101

1 Answers1

1

Add spaces to the end when tab is hit:

document.querySelector('#text').addEventListener('keydown', e => {
    if (e.keyCode == 9) {
        e.preventDefault();
        document.querySelector('#text').value += "    ";
    }
});

Edit: Worked on inserting spaces and I think this works:

<textarea id="text"></textarea>
document.querySelector('#text').addEventListener('keydown', e => {
    if (e.keyCode == 9) {
        e.preventDefault();

        var ele = document.querySelector('#text');
        var caretPos = ele.selectionStart;
        var textAreaTxt = ele.value;
        var txtToAdd = "    ";
        ele.value = textAreaTxt.substring(0, caretPos) 
                    + txtToAdd 
                    + textAreaTxt.substring(caretPos);
        ele.selectionStart = caretPos + 4;
        ele.selectionEnd = caretPos + 4;
    }
});

With help from https://stackoverflow.com/a/15977052/1171702 and a general search for js add spaces at cursor position.

wazz
  • 4,953
  • 5
  • 20
  • 34
  • and what if the cursor is not at the end? – epascarello Nov 01 '19 at 19:33
  • touche! that's a problem. not sure how to find the cursor off the top of my head. anyone? Edit: did a quick search and this has been asked before, more or less. -- get the cursor position, cut/save the text from there to the end, add spaces, replace the text. – wazz Nov 01 '19 at 19:35
  • 1
    +1 fyi, [`document.execCommand.insertText`](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) would let you avoid all the `element.selectionStart` and `element.selectionEnd` shenanigans, except that firefox doesn't currently support it on form elements ([firefox bug 1220696](https://bugzilla.mozilla.org/show_bug.cgi?id=1220696)). – Woodrow Barlow Nov 01 '19 at 20:45