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

7th Aug 2024, 9:15 AM
Akash Mahato
Akash Mahato - avatar
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
7th Aug 2024, 9:42 AM
Bob_Li
Bob_Li - avatar
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...
7th Aug 2024, 9:41 AM
Ipang
0
I would save data in local storage provides by web browser
7th Aug 2024, 11:17 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
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?
14th Aug 2024, 1:06 PM
Akash Mahato
Akash Mahato - avatar