undoredo.js
Version:
A powerful and simple Javascript library provides a history for undo/redo functionality. Just like a time machine! 🕐
61 lines (57 loc) • 2.65 kB
HTML
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<title>UndoRedo.js - Textarea Example</title>
</head>
<body>
<div style="max-width: 800px;" class="container p-3">
<textarea class="form-control" id="input" style="height: 341px; width: 100%;"></textarea>
<br>
<div class="row">
<button id="undo" style="margin: 5px;" class="btn btn-danger btn-lg col">undo</button>
<button id="redo" style="margin: 5px;" class="btn btn-warning btn-lg col">redo</button>
</div>
</div>
<script src="./src/UndoRedo.js"></script>
<script>
// Require the library function
const txtHistory = new window.UndoRedojs(5)
// Get the textarea
const textarea = document.querySelector("#input")
// Add event listener for inputs on the textarea
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)
}
}
})
// 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)
// The undo button
document.querySelector("#undo").addEventListener('click', () => {
if (txtHistory.undo(true) !== undefined) {
textarea.value = txtHistory.undo()
}
})
// The redo button
document.querySelector("#redo").addEventListener('click', () => {
if (txtHistory.redo(true) !== undefined) {
textarea.value = txtHistory.redo()
}
})
</script>
</body>
</html>