Undo/Redo And History In Text Field – UndoRedo.js

Category: Form , Javascript | April 2, 2020
Author: iMrDJAi
Views Total: 274 views
Official Page: Go to website
Last Update: April 2, 2020
License: MIT

Preview:

Undo/Redo And History In Text Field – UndoRedo.js

Description:

UndoRedo.js is a JavaScript library that applies undo and redo functionalities to text fields.

The plugin provides a History function that records what you typed for the undo and redo functionalities.

Basic usage:

1. Import the UndoRedo.js library into the document.

<script src="src/UndoRedo.js"></script>

2. Initialize the UndoRedo.js library and determine the cooldown used for recording the data.

const txtHistory = window.UndoRedojs(5);

3. Add event listeners for inputs on your text field.

<textarea id="input"></textarea>
const textarea = document.querySelector("#input");

textarea.addEventListener('input', () => {
  // Check if the new textarea value is different
  if (txtHistory.current() !== textarea.value) {
    // Check for pastes, auto corrects..
    if ((textarea.value.length - txtHistory.current().length) > 1 || (textarea.value.length - txtHistory.current().length) < -1 || (textarea.value.length - txtHistory.current().length) === 0) {
      // Record the textarea value and force to bypass cooldown
      txtHistory.record(textarea.value, true);
    // Check for single key press, single chacacter paste..
    } else {
      // Record the textarea value
      txtHistory.record(textarea.value);
    }
  }
});

4. Some browsers will auto-fill the textarea again after reloading, this will deal with that.

setTimeout(() => {
  if (textarea.value) txtHistory.record(textarea.value, true);
}, 100);

5. Enable the undo/redo functionalities.

if (txtHistory.undo(true) !== undefined) {
  textarea.value = txtHistory.undo();
}

if (txtHistory.redo(true) !== undefined) {
  textarea.value = txtHistory.redo();
}

Changelog:

v1.0.2 (04/02/2020)

  • Fixed a typo on name.

You Might Be Interested In:


Leave a Reply