indent-textarea

Add editor-like tab-to-indent functionality to <textarea>, in a few bytes


Keywords
text area, tab, indent, indentation, editor
License
MIT
Install
npm install indent-textarea@1.0.1

Documentation

indent-textarea Build Status

Add editor-like tab-to-indent functionality to <textarea>, in a few bytes

  • Supports the native undo functionality (ctrl+z, cmd+z, context menu), as seen in the gif on the side.
  • Supports also Firefox (a lot of solutions online don't because of bugs and deprecations) but without undo support.

This only supports tabbing on the current line but it doesn't preserve it for the next line like a full code editor would (e.g. when pressing enter). 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.

Install

npm install indent-textarea

Setup

const indentTextarea = require('indent-textarea');
import indentTextarea from 'indent-textarea';

Usage

Once, one element

This will add a tab where the caret/selection is in the textarea. It's not meant to be used directly.

const textarea = document.querySelector('textarea');
indentTextarea(textarea);

When the user presses tab

One element

const textarea = document.querySelector('textarea');
indentTextarea.watch(textarea);

Array/NodeList/Iterable of elements

const textareas = document.querySelectorAll('textarea');
indentTextarea.watch(textareas);

With a selector

The selector is run once, so it's equivalent to the example above.

indentTextarea.watch('textarea');

Related

  • fit-textarea - Automatically expand a <textarea> to fit its content, in a few bytes.
  • delegate-it - DOM event delegation, in <1KB. Can be used to attach one indent-textarea to many elements.
  • Refined GitHub - Uses this module.