Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo TAB in textarea

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"?

like image 464
Goover Avatar asked Oct 18 '25 16:10

Goover


1 Answers

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

like image 101
Marcus Avatar answered Oct 20 '25 05:10

Marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!