JavaScript - Allow tab input in textarea
A method and simple code example to allow tab input in a textarea using JavaScript.
The HTML has a textarea that allows tab input.
<textarea id="target" placeholder="This textarea allows tab input."></textarea>
The textarea input event is implemented with addEventListener()
.
The entered key is checked if it is "Tab" with "event.key".
Default form movement behavior is disabled with "event.preventDefault()
".
The tab is input using document.execCommand()
.
The cursor position is also set to the expected position after tab input.
document.querySelector('#target').addEventListener('keydown', () => {
if (event.key === "Tab") {
// Disable the default behavior
event.preventDefault();
// Get the cursor position during input
let selectionPosition = event.target.selectionStart;
// Insert a tab character at the cursor position
document.execCommand('insertText', false, '\t');
// Restore the cursor position
event.target.selectionStart = event.target.selectionEnd = selectionPosition + 1;
}
});