3

There are many questions about how to prevent focusing next element, when pressing TAB in textarea tag and just insert a \t character. Or any other character. All of them are answered with something like:

  1. Capture a TAB keypress
  2. Get current caret position and selection info
  3. Replace the value so it will contain \t or whatever user wants.

All this works fine until you'll press "Undo" or CTRL+Z after TAB

If you do this, you will experience some side effects depending on the browser you use:

  • Firefox will remove \t but caret pos will go to the end and all text in textarea are selected
  • Chrome will not count this \t as user input so CTRL+Z will undo pre-last operation, leaving \t in place, there is also some caret problems which are hard to predict
  • IE is acting same as Chrome

You can watch this here http://jsfiddle.net/c7zc8/1/

The question is how to make it crossbrowser and "undoable"?

Goover
  • 380
  • 1
  • 3
  • 13

1 Answers1

2

For the latest Chrome (33), the following works:

var ta = document.getElementById("textareaId");
ta.addEventListener("keydown", function(e) {
    if (e.which===9) {
        e.preventDefault();
        document.execCommand("insertText", false, "\t");
    }
}, false);

Reference: Javascript textarea undo redo

For IE, however, there is no perfect solution. IE11 has ms-beginUndoUnit and ms-endUndoUnit, but even that does not work perfectly according to Tim Down in internet explorer alternative to document.execCommand("insertText",...), for text insertion that can be undone/redone by the user

Community
  • 1
  • 1
Marcus
  • 3,459
  • 1
  • 26
  • 25