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:
\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:
\t
but caret pos will go to the end and all text in textarea are selected\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 predictYou can watch this here http://jsfiddle.net/c7zc8/1/
The question is how to make it crossbrowser and "undoable"?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With