0

I have this Javascript below. It counts up (it says Countdown but it's been modified to "countup" now from 00). But when the browser has been refreshed or come back to the page, then the counter starts from 00 again. Is there a way to add a cookie to it or some other code so that it remembers the count it was at for the session someone is browsing a site?

     <script type="text/javascript">
        function pad(num, size) {
  var s = num + "";
  while (s.length < size) s = "0" + s;
  return s;
}

function initCountdown() {
  setTimeout(function() {
    current_wait++;

    if (current_wait <= waits.length) {
      var countdowns = document.getElementsByClassName('countdown'); 

      for (var i = 0; i < countdowns.length; i++) {
        var number = parseInt(countdowns[i].innerHTML);
        number++;

        countdowns[i].innerHTML = pad(number, 2);
      }

      initCountdown();
    }
  }, waits[current_wait] * 1000);
}

var initial_number = 0;
var waits = [2, 8, 16, 26, 44, 66, 88, 99, 121]; //t-val
var current_wait = 0;

var countdowns = document.getElementsByClassName('countdown');

for (var i = 0; i < countdowns.length; i++) {
  countdowns[i].innerHTML = pad(initial_number, 2);
}

initCountdown();
    </script>
Reporter
  • 3,897
  • 5
  • 33
  • 47
Jenny
  • 11
  • 3
  • Take a look at https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie – Reporter Feb 28 '19 at 09:51
  • [Local Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) might help. – CodeF0x Feb 28 '19 at 09:54
  • `Is there a way to add a cookie to it` - yes, there is. Have you done any basic research on using cookies in Javascript? – Robin Zigmond Feb 28 '19 at 09:55
  • I could spend days and likely still not figure it out. That's why I'm here. It's this or fiverr. I'll check though on what you're saying. But I don't know javascript at all so it's pretty complicated for me unfortunately. But thanks. – Jenny Mar 01 '19 at 13:26
  • Is this cookie thing really that complicated??? – Jenny Mar 01 '19 at 22:29

1 Answers1

0

If the information you want to store doesn't require to send to your server side program, you can use HTML5 sessionStorage or localSotrage to store information in client web browser.

Please take a look on the exmaples on W3CSchool, they actually have a click counter example that similar to what you need.

Solomon Tam
  • 739
  • 3
  • 11