Skip to content

Commit 18ae456

Browse files
committed
feat(JS): making data persistent even after a page refresh, by using local storage.
1 parent b11d2b3 commit 18ae456

File tree

1 file changed

+50
-8
lines changed

1 file changed

+50
-8
lines changed

index.js

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@ clearHistoryBtn.addEventListener("click", () => {historyElement.innerHTML = "";
1212

1313
document.addEventListener('keydown', handleKeyPress);
1414

15+
16+
// Add this at the beginning of your script
17+
window.addEventListener("DOMContentLoaded", () => {
18+
const history = getHistoryFromLocalStorage();
19+
history.forEach((entry) => {
20+
createHistoryList(entry, historyElement);
21+
});
22+
});
23+
24+
1525
function handleKeyPress(event) {
1626

1727
const key = event.key;
@@ -266,21 +276,53 @@ function displayResult(array, outcome) {
266276
array.push(outcome);
267277
}
268278

269-
function createHistoryList(array, element, history) {
270-
array.forEach((entry) => {
271-
history.push(entry);
272-
element.innerHTML += `<li> ${entry.join(" ")}</li>`;
273-
if (element.childElementCount > HISTORY_LIMIT) {
274-
element.firstElementChild.remove();
275-
}
276-
});
279+
// function createHistoryList(array, element) {
280+
281+
// array.forEach((entry) => {
282+
// history.push(entry);
283+
// element.innerHTML += `<li> ${entry.join(" ")}</li>`;
284+
// if (element.childElementCount > HISTORY_LIMIT) {
285+
// element.firstElementChild.remove();
286+
// }
287+
// });
288+
// }
289+
290+
function createHistoryList(array, element) {
291+
const history = getHistoryFromLocalStorage();
292+
history.push(array);
293+
setHistoryToLocalStorage(history);
294+
295+
element.innerHTML += `<li> ${array.join(" ")}</li>`;
296+
297+
if (element.childElementCount > 10) {
298+
element.firstElementChild.remove();
299+
}
277300
}
301+
302+
function getHistoryFromLocalStorage() {
303+
return JSON.parse(localStorage.getItem("calculatorHistory")) || [];
304+
}
305+
306+
function setHistoryToLocalStorage(history) {
307+
localStorage.setItem("calculatorHistory", JSON.stringify(history));
308+
}
309+
310+
311+
312+
313+
278314
clearHistoryBtn.addEventListener("click", () => {
279315
historyElement.innerHTML = "";
316+
clearHistoryInLocalStorage();
280317
togglesClearHistoryButton(historyElement, clearHistoryBtn);
281318
});
282319

320+
function clearHistoryInLocalStorage() {
321+
localStorage.removeItem("calculatorHistory");
322+
}
323+
283324
function togglesClearHistoryButton(element, btn) {
325+
const history = getHistoryFromLocalStorage();
284326
btn.classList.toggle("display", element.childElementCount > 0);
285327
}
286328
// functions creations ends

0 commit comments

Comments
 (0)