Skip to content
Insert text in a textarea (supports Firefox and Undo, where possible)
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.editorconfig Initial version Mar 27, 2019
.gitignore Initial version Mar 27, 2019
.npmrc Initial version Mar 27, 2019
.travis.yml Add tests Apr 17, 2019
index.ts Improve internal types Apr 17, 2019
license Initial version Mar 27, 2019
package.json 1.0.3 Apr 17, 2019
readme.md Readme: Fix build badge Jun 6, 2019
test.js Add tests Apr 17, 2019
tsconfig.json Initial version Mar 27, 2019

readme.md

insert-text-textarea (size) (status)

Insert text in a textarea (supports Firefox and Undo, where possible)

The text will be inserted after the cursor and it will replace any text that's selected, acting like a paste would.

This is useful when creating "editor" buttons, to add text or wrap the selected text. For example, this module is used by indent-textarea.

An input event will also be dispatched, with event.inputType === 'insertText'.

It uses document.execCommand('insertText') in Chrome (which has Undo support) and it replicates its behavior in Firefox (without Undo support until this bug is solved).

If you need IE support, use insert-text-at-cursor.

Install

npm install insert-text-textarea

Setup

const insertText = require('insert-text-textarea');
import insertText from 'insert-text-textarea';

Usage

const textarea = document.querySelector('textarea');
const button = document.querySelector('.js-add-signature');
button.addEventListener(event => {
	// It will add this text at the cursor, replacing any possible selected text
	insertText(textarea, 'Made by 🐝 with pollen.');
});
const textarea = document.querySelector('textarea');
const button = document.querySelector('.js-markdown-make-text-bold');
button.addEventListener(event => {
	// This will replace the selected text (if any) with **selected text**
        // Don't use `getSelection()` if you want Firefox support
	const selectedText = value.slice(
		textarea.selectionStart,
		textarea.selectionEnd
	);
	insertText(textarea, '**' + selectedText + '**');
});

Related

  • indent-textarea - Add editor-like tab-to-indent functionality to <textarea>, in a few bytes. Uses this module.
  • fit-textarea - Automatically expand a <textarea> to fit its content, in a few bytes.
  • Refined GitHub - Uses this module.
You can’t perform that action at this time.