Add editor-like tab-to-indent functionality to <textarea>, in a few bytes
MIT License
Add editor-like tab-to-indent functionality to
<textarea>
, in a few bytes
Try the demo.
This only supports tab and shift+tab but it doesn't preserve it on enter like a full code editor would. If you need a more complete solution, check out behave.js (outdated, no undo) or CodeMirror (much heavier).
Note: the API used (document.execCommand
) will trigger multiple input
events when multiple lines are selected, so if you have a listener on the textarea
, make sure to debounce it.
You can download the standalone bundle
Or use npm
:
npm install indent-textarea
// This module is only offered as a ES Module
import {enableTabToIndent} from 'indent-textarea';
You can listen to tab and shift+tab to indent and unindent respectively.
const textarea = document.querySelector('textarea');
enableTabToIndent(textarea);
If you prefer event delegation:
import delegate from 'delegate-it';
import {tabToIndentListener} from 'indent-textarea';
delegate(document.body, 'textarea', 'keydown', tabToIndentListener);
If you prefer the raw indentSelection
/unindentSelection
methods, they're also available below.
Adds tab and shift+tab event listeners to the provided textarea
(s). It also listens to esc to blur/unfocus the field and allow the user to keep tabbing.
Type: HTMLTextAreaElement
string
Iterable<HTMLTextAreaElement>
This can be:
<textarea>
DOM elementdocument.querySelectorAll
(it will watch all the selected elements)This is an AbortSignal
that allows you to remove/disable the listener
const controller = new AbortController();
const textarea = document.querySelector('textarea');
enableTabToIndent(textarea, controller.signal);
// And then later, to stop listening
controller.abort();
Raw method to indent the selected text in the provided <textarea>
element, once, instantly.
Type: HTMLTextAreaElement
Raw method to unindent the selected text in the provided <textarea>
element, once, instantly.
Type: HTMLTextAreaElement
Type: (event: KeyboardEvent) => void
Raw event handler used by enableTabToIndent
or to use manually via addEventListener
document.querySelector('textarea').addEventListener('keydown', tabToIndentListener);
Or with event delegation:
import delegate from 'delegate-it';
import {tabToIndentListener} from 'indent-textarea';
delegate(document.body, 'textarea', 'keydown', tabToIndentListener);
<textarea>
to fit its content, in a few bytes.indent-textarea
to many elements.MIT © Federico Brigante