0
How do you retain the state of a webpage on window refresh?
I'm trying to build a counter, when you refresh the page it should retain the state or counter value on window refresh? This code below has been cited from one of the members of stack overflow community. <button>clicked 0 times</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> let count = 0; $('button').click(function(){ count++; $(this).text("clicked " + count+" times") }); I'm new to programming, I'm trying to build a counter to store or retain value on page refresh
4 odpowiedzi
+ 3
you would need access to localStorage or sessionStorage. It is doable in browsers, but not in Sololearn app.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Here is a counter that survives page refresh.
I referenced it from a public github repo I got after a quick Google search.
Link to source:
https://github.com/TylerPottsDev/yt-js-counter
I modified it a bit, but kept the useful parts.
It does not save to localStorage in Sololearn app, though. But I tested it in browsers and it works.
https://sololearn.com/compiler-playground/W4kXQuyp3sp6/?ref=app
0
What type of counter are you planning to work on? can you perhaps provide more details?
Depending on whether you are already accustomed and/or comfortable to using jQuery, a simple button click counter can be done with plain javascript.
More details please...
0
I would save data in local storage provides by web browser
0
function ditm() {
let counter = 0;
let localStorageAllowed = false;
try {
counter = localStorage.getItem("count", count);
localStorageAllowed = true;
if (localStorageAllowed) {
localStorage.setItem("counter", counter);
const span = document.getElementById("#otpt");
span.textContent = counter;
} else {
// console.log("No localstorage for you");
}
} catch {}
let rlt = document.getElementById("otpt");
let curVal = Number(rlt.textContent) + 1;
rlt.textContent = curVal;
}
Here is my code, what Im trying to do is using the local storage within the function in a try catch block, what am i missing?