Here, this was done in a previous thread and very much along the same lines as dennisjn is suggesting, but using localStorage instead.
const TEXTSTORE = "text-store";
// start by clearing previous storage
localStorage.removeItem(TEXTSTORE);
const retrieveText = () => {
// will retrieve the stored data, which is in string format
// and JSON.parse will convert that into a usuable array
const storedText = JSON.parse(localStorage.getItem(TEXTSTORE));
// if nothing has been stored then return with false
if (storedText === null) {
return false;
}
// let's just check that we have an array
if (Array.isArray(storedText)) {
// retrieve last item stored in array.
// pop will mutate the storedText array, removing the last item
const lastText = storedText.pop();
// now the array has one less item, overwrite the previous store
localStorage.setItem(TEXTSTORE, JSON.stringify(storedText));
// return lastText
return lastText;
}
return false;
};
const storeText = (text) => {
const storedText = JSON.parse(localStorage.getItem(TEXTSTORE));
// if this is the first time storing then create our text store
// saving an array with our first bit of text
if (storedText === null) {
localStorage.setItem(TEXTSTORE, JSON.stringify([text]));
return; // return early
}
if (Array.isArray(storedText)) {
// add new text to end of array
storedText.push(text);
// overwrite text store with ammended array
localStorage.setItem(TEXTSTORE, JSON.stringify(storedText));
}
};
and …
document.querySelectorAll(".wrap-with").forEach((button) =>
button.addEventListener("click", (event) => {
const textArea = document.querySelector("#myTextarea");
storeText(textArea.value);
wrapWith(event.target, textArea);
})
);
document.querySelector(".undo").addEventListener("click", () => {
const textArea = document.querySelector("#myTextarea");
// retrieve last change
const lastText = retrieveText();
// if there is a change then amend the text area
if (lastText) {
textArea.value = lastText;
}
});
I think joon1 is having another go at this. This is the previous thread