Skip to content

Instantly share code, notes, and snippets.

@bewarusman
Last active August 15, 2023 12:53
Show Gist options
  • Save bewarusman/e9ecc5f5d5cb30a0734ec428e0aaae5a to your computer and use it in GitHub Desktop.
Save bewarusman/e9ecc5f5d5cb30a0734ec428e0aaae5a to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Online Text Editor</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
/>
</head>
<body>
<div class="container mt-5">
<div class="row mb-3">
<div class="col-12">
<textarea id="editor" class="form-control" rows="10"></textarea>
</div>
</div>
<div class="row">
<div class="col-12">
<button id="undoButton">Undo</button>
<button id="redoButton">Redo</button>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Stack class implementation
function Stack() {
this.dataStore = [];
this.top = 0;
}
Stack.prototype.push = function (element) {
this.dataStore[this.top++] = element;
};
Stack.prototype.pop = function () {
return this.dataStore[--this.top];
};
Stack.prototype.peek = function () {
return this.dataStore[this.top - 1];
};
Stack.prototype.count = function () {
return this.top;
};
Stack.prototype.clear = function () {
this.top = 0;
};
// end of: Stack class implementation
// html elements
const editor = document.getElementById("editor");
const undoButton = document.getElementById("undoButton");
const redoButton = document.getElementById("redoButton");
// event listeners for: undo and redo buttons
undoButton.addEventListener("click", undo);
redoButton.addEventListener("click", redo);
const undoStack = new Stack();
const redoStack = new Stack();
// update the editor's content: after undo or redo
function updateEditorContent(content) {
editor.value = content;
}
// handle undo action
function undo() {
if (undoStack.count() === 0) return;
const currentContent = editor.value;
redoStack.push(currentContent);
const previousContent = undoStack.pop();
updateEditorContent(previousContent);
}
// handle redo action
function redo() {
if (redoStack.count() === 0) return;
const currentContent = editor.value;
undoStack.push(currentContent);
const nextContent = redoStack.pop();
updateEditorContent(nextContent);
}
// Listen for input changes in the editor
editor.addEventListener("input", () => {
undoStack.push(editor.value);
redoStack.clear(); // Clear redo stack
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment