How to make a div editable in HTML5 using javascript and store it’s history of change?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our W3Make Forum to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
you can utilize the contenteditable attribute and handle the change events using JavaScript.
HTML –
Editable content
Undo
Redo
var editableDiv = document.getElementById("editableDiv");
var undoBtn = document.getElementById("undoBtn");
var redoBtn = document.getElementById("redoBtn");
// Array to store the history of changes
var history = [];
var currentPosition = -1;
function saveState() {
var content = editableDiv.innerHTML;
history.push(content);
currentPosition++;
}
// to undo the last change
function undo() {
if (currentPosition > 0) {
currentPosition--;
editableDiv.innerHTML = history[currentPosition];
}
}
// to redo the last undone change
function redo() {
if (currentPosition < history.length - 1) {
currentPosition++;
editableDiv.innerHTML = history[currentPosition];
}
}
// change events in the editable div
editableDiv.addEventListener("input", function() {
saveState();
});
//for undo and redo buttons
undoBtn.addEventListener("click", function() {
undo();
});
redoBtn.addEventListener("click", function() {
redo();
});
Hope this will help(: