skip to Main Content

I got this count down for my shopify website and it works just fine, except for when you refresh the page. When you do that the thing just resets itself. Can anyone please help me to fix this? Thank you in advance!

This is the code:

<style>#progress_bar{margin-top:15px}.progressbar.progressbar{background:#ffe8e8;border:0px solid whitesmoke;height:11px}.progressbar.progressbar div{background:#d95350;height:11px}{border-radius:16px}.progressbar.progressbar.active div{-webkit-animation:2s linear 0s normal none infinite running progress-bar-stripes;animation:2s linear 0s normal none infinite running progress-bar-stripes}.progress-striped.progressbar.progressbar div{background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, rgba(0, 0, 0, 0) 25%, rgba(0, 0, 0, 0) 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, rgba(0, 0, 0, 0) 75%, rgba(0, 0, 0, 0));background-size:40px 40px}.items-count{margin-top:0px;margin-bottom:0px}.count{color:#a94442;padding:1px}.items-count p{padding-bottom:5px;margin:0;text-transform:uppercase;font-weight:700;text-align:center;font-family:"DIN Next",Arial,sans-serif}.progressbar{position:relative;display:block;background-color:#ca0000;border:1px solid #ddd;margin-bottom:15px;-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, .1);box-shadow:inset 0 1px 2px rgba(0, 0, 0, .1)}.progressbar > div{background-color:#ca0000;width:0;margin-bottom:0;height:15px}.progressbar > div.less-than-ten{background-color:#ca0000 !important}#clock-ticker{display:block;margin-bottom:15px}#clock-ticker .block{position:relative;color:#000;font-weight:bold;float:left;text-align:center;width:25%}#clock-ticker .block .flip-top{width:88px;height:39px;line-height:40px;font-size:40px;text-align:center}#clock-ticker .block .label,span.flip-top{color:#000;font-weight:bold;text-align:center;font-size:14px;text-transform:uppercase;width:88px;line-height:25px;font-family:"Open Sans",Arial,sans-serif}</style><style>.progressbar div{border-radius:20px}</style><style>#progress_bar div{border-radius:20px}</style>

<script type="text/javascript">
function randomIntFromInterval(min, max) {return Math.floor(Math.random() * (max - min + 1) + min);}

// Settings are here
var total_items = 50;
var d = new Date();
var min_items_left = 8;
var max_items_left = 12;
var remaining_items = randomIntFromInterval(min_items_left, max_items_left);
var min_of_remaining_items = 3;
var decrease_after = 1.7; 
var decrease_after_first_item = 0.17; 

// Davy Jones' Locker
(function($){$.fn.progressbar=function(){var a="<p>Only <span class='count'>"+remaining_items+"</span> items remaining</p>"+"<div class='progressbar'><div style='width:100%'></div></div>";this.addClass('items-count');this.html(a+this.html());updateMeter(this);var b=this;setTimeout(function(){remaining_items--;if(remaining_items<min_of_remaining_items){remaining_items=randomIntFromInterval(min_items_left,max_items_left)}$('.count').css('background-color','#CE0201');$('.count').css('color','#fff');setTimeout(function(){$('.count').css('background-color','#fff');$('.count').css('color','#CE0201')},1000*60*0.03);b.find(".count").text(remaining_items);updateMeter(b)},1000*60*decrease_after_first_item);setInterval(function(){remaining_items--;if(remaining_items<min_of_remaining_items){remaining_items=randomIntFromInterval(min_items_left,max_items_left)}$('.count').css('background-color','#CE0201');$('.count').css('color','#fff');setTimeout(function(){$('.count').css('background-color','#fff');$('.count').css('color','#CE0201')},1000*60*0.03);b.find(".count").text(remaining_items);updateMeter(b)},1000*60*decrease_after)};function updateMeter(a){var b=100*remaining_items/total_items;if(remaining_items<10){a.find('.progressbar div:first').addClass('less-than-ten')}a.find('.progressbar').addClass('active progress-striped');setTimeout(function(){myanimate(a.find('.progressbar div:first'),b);a.find('.progressbar').removeClass('active progress-striped')},1000)}}(jQuery));function myanimate(a,b){var c=0;var d=parseInt(a.closest('.progressbar').css('width'));var e=Math.floor(100*parseInt(a.css('width'))/d);if(e>b){c=e}function frame(){if(e>b){c--}else{c++}a.css('width',c+'%');if(c==b||c<=0||c>=100)clearInterval(f)}var f=setInterval(frame,40)} jQuery.noConflict()(function($){$(document).ready(function(){$("#progress_bar").progressbar();var tag="ctdn-12-12".match(/d+/g);var hour=14;var theDaysBox=$("#numdays");var theHoursBox=$("#numhours");var theMinsBox=$("#nummins");var theSecsBox=$("#numsecs");var d=new Date();var n=d.getDay();var date=1;var gg=0;var hh=0;var ii=0;var nsec=0-d.getSeconds();if(nsec<0){nsec=60-d.getSeconds();gg=1}var nmin=0-d.getMinutes()-gg;if(nmin<0){nmin=60-d.getMinutes()-gg;hh=1}var nhrs=14-d.getHours()-hh;if(nhrs<0){nhrs=38-d.getHours()-hh;ii=1}var ndat=date-1;if(ndat<0){var mmon=d.getMonth();ndat=30+date-d.getDate()-ii}theSecsBox.html(nsec);theMinsBox.html(nmin);theHoursBox.html(nhrs);theDaysBox.html(ndat);var refreshId=setInterval(function(){var e=theSecsBox.text();var a=theMinsBox.text();var c=theHoursBox.text();var b=theDaysBox.text();if(e==0&&a==0&&c==0&&b==0){}else{if(e==0&&a==0&&c==0){theDaysBox.html(b-1);theHoursBox.html("23");theMinsBox.html("59");theSecsBox.html("59")}else{if(e==0&&a==0){theHoursBox.html(c-1);theMinsBox.html("59");theSecsBox.html("59")}else{if(e==0){theMinsBox.html(a-1);theSecsBox.html("59")}else{theSecsBox.html(e-1)}}}}},1000);});});</script>```

2

Answers


  1. You can achieve that using SessionStorage. Store the count for day, hour, minute and second in SessionStorage using web storage API.

    https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API

    When the page reloads read the values set in sessionStorage, if found. If not use the usual values extracted from Date().

    You can run the stack snippet shown below to view normal operation. Stack snippet doesn’t allow reading ‘sessionStorage’ property from ‘Window’ as the document is sandboxed and lacks the ‘allow-same-origin’ flag.

    So i have commented the code that i have inserted and also set if conditions to be changed later when you run the code in real environment. In the snippet below it’s:
    if (false && sessionStorage)
    you can run this code in your browser by changing those if conditions to:
    if (sessionStorage)
    You will see the counter value is retained on page refresh.

    function randomIntFromInterval(min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min);
    }
    
    // Settings are here
    var total_items = 50;
    var d = new Date();
    var min_items_left = 8;
    var max_items_left = 12;
    
    // declare storage keys first here, it's easy to manage that way.
    const StorageKeys = {
      counterItems: 'my-counter-items',
      counter: 'my-counter'
    };
    
    /** Start: Insert this code to read session Storage for counter Items **/
    // here you can pull the sessionStored value 
    let counterItems = null;
    // NOTE: remove false from condition check before running in real env
    if (false && sessionStorage) {
     counterItems = sessionStorage.getItem(StorageKeys.counterItems);
    }
    /** End: Insert this code to read session Storage for counter Items **/
    
    // use stored items count if present
    var remaining_items = counterItems ? Number(counterItems) : randomIntFromInterval(min_items_left, max_items_left);
    
    var min_of_remaining_items = 3;
    var decrease_after = 1.7;
    var decrease_after_first_item = 0.17;
    
    // Davy Jones' Locker
    (function($) {
      $.fn.progressbar = function() {
        var a = "<p>Only <span class='count'>" + remaining_items + "</span> items remaining</p>" + "<div class='progressbar'><div style='width:100%'></div></div>";
        this.addClass('items-count');
        this.html(a + this.html());
        updateMeter(this);
        var b = this;
        setTimeout(function() {
          remaining_items--;
          if (remaining_items < min_of_remaining_items) {
            remaining_items = randomIntFromInterval(min_items_left, max_items_left)
          }
          $('.count').css('background-color', '#CE0201');
          $('.count').css('color', '#fff');
          setTimeout(function() {
            $('.count').css('background-color', '#fff');
            $('.count').css('color', '#CE0201')
          }, 1000 * 60 * 0.03);
          b.find(".count").text(remaining_items);
          updateMeter(b)
        }, 1000 * 60 * decrease_after_first_item);
        setInterval(function() {
          remaining_items--;
          if (remaining_items < min_of_remaining_items) {
            remaining_items = randomIntFromInterval(min_items_left, max_items_left)
          }
          $('.count').css('background-color', '#CE0201');
          $('.count').css('color', '#fff');
          setTimeout(function() {
            $('.count').css('background-color', '#fff');
            $('.count').css('color', '#CE0201')
          }, 1000 * 60 * 0.03);
          b.find(".count").text(remaining_items);
          updateMeter(b)
        }, 1000 * 60 * decrease_after)
      };
    
      function updateMeter(a) {
        /** Start: Insert this code to set session Storage for counter Items **/
        // now save the counter items values in sessionStorage
        // NOTE: remove false from condition check before running in real env
        if(false && sessionStorage) {
          sessionStorage.setItem(StorageKeys.counterItems, remaining_items);
        }
        /** End: Insert this code to set session Storage for counter Items **/
        
        var b = 100 * remaining_items / total_items;
        if (remaining_items < 10) {
          a.find('.progressbar div:first').addClass('less-than-ten')
        }
        a.find('.progressbar').addClass('active progress-striped');
        setTimeout(function() {
          myanimate(a.find('.progressbar div:first'), b);
          a.find('.progressbar').removeClass('active progress-striped')
        }, 1000)
      }
    }(jQuery));
    
    function myanimate(a, b) {
      var c = 0;
      var d = parseInt(a.closest('.progressbar').css('width'));
      var e = Math.floor(100 * parseInt(a.css('width')) / d);
      if (e > b) {
        c = e
      }
    
      function frame() {
        if (e > b) {
          c--
        } else {
          c++
        }
        a.css('width', c + '%');
        if (c == b || c <= 0 || c >= 100) clearInterval(f)
      }
      var f = setInterval(frame, 40)
    }
    
    jQuery.noConflict()(function($) {
      $(document).ready(function() {
        $("#progress_bar").progressbar();
        var tag = "ctdn-12-12".match(/d+/g);
        var hour = 14;
        var theDaysBox = $("#numdays");
        var theHoursBox = $("#numhours");
        var theMinsBox = $("#nummins");
        var theSecsBox = $("#numsecs");
        var d = new Date();
        var n = d.getDay();
        var date = 1;
        var gg = 0;
        var hh = 0;
        var ii = 0;
        var nsec = 0 - d.getSeconds();
        if (nsec < 0) {
          nsec = 60 - d.getSeconds();
          gg = 1
        }
        var nmin = 0 - d.getMinutes() - gg;
        if (nmin < 0) {
          nmin = 60 - d.getMinutes() - gg;
          hh = 1
        }
        var nhrs = 14 - d.getHours() - hh;
        if (nhrs < 0) {
          nhrs = 38 - d.getHours() - hh;
          ii = 1
        }
        var ndat = date - 1;
        if (ndat < 0) {
          var mmon = d.getMonth();
          ndat = 30 + date - d.getDate() - ii
        }
        
        /** Start: Insert this code to read session Storage **/
        // here read from Session Storage; you can use any
        // keyname to store the values
        let counterData = null;
        // NOTE: remove false from condition check before running in real env
        if(false && sessionStorage) {
          counterData = JSON.parse(sessionStorage.getItem(StorageKeys.counter));
        }
        /** End: Insert this code to read session Storage **/
       
        // use the stored valued value if present
        theSecsBox.html(counterData ? counterData.nsec : nsec);
        theMinsBox.html(counterData ? counterData.nmin : nmin);
        theHoursBox.html(counterData ? counterData.nhrs : nhrs);
        theDaysBox.html(counterData ? counterData.ndat : ndat);
        
        var refreshId = setInterval(function() {
          var e = theSecsBox.text();
          var a = theMinsBox.text();
          var c = theHoursBox.text();
          var b = theDaysBox.text();
          
          /** Start: Insert this code to set session Storage **/
          // now save the counter values in sessionStorage
          // NOTE: remove false from condition check before running in real env
          if(false && sessionStorage) {
            const currentValues = { nsec: e, nmin: a, nhrs: c, ndat: b };
            sessionStorage.setItem(StorageKeys.counter, JSON.stringify(currentValues));
          }
          /** End: Insert this code to set session Storage **/
                
          if (e == 0 && a == 0 && c == 0 && b == 0) {} else {
            if (e == 0 && a == 0 && c == 0) {
              theDaysBox.html(b - 1);
              theHoursBox.html("23");
              theMinsBox.html("59");
              theSecsBox.html("59")
            } else {
              if (e == 0 && a == 0) {
                theHoursBox.html(c - 1);
                theMinsBox.html("59");
                theSecsBox.html("59")
              } else {
                if (e == 0) {
                  theMinsBox.html(a - 1);
                  theSecsBox.html("59")
                } else {
                  theSecsBox.html(e - 1)
                }
              }
            }
          }
        }, 1000);
      });
    });
    body {
      background-color: #fff;
    }
    
    #progress_bar {
      margin-top: 15px;
    }
    
    .progressbar.progressbar {
      background: #ffe8e8;
      border: 0px solid whitesmoke;
      height: 11px;
    }
    
    .progressbar.progressbar div {
      background: #d95350;
      height: 11px;
    }
    
      {
      border-radius: 16px;
    }
    
    .progressbar.progressbar.active div {
      -webkit-animation: 2s linear 0s normal none infinite running progress-bar-stripes;
      animation: 2s linear 0s normal none infinite running progress-bar-stripes;
    }
    
    .progress-striped.progressbar.progressbar div {
      background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
      background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, rgba(0, 0, 0, 0) 25%, rgba(0, 0, 0, 0) 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, rgba(0, 0, 0, 0) 75%, rgba(0, 0, 0, 0));
      background-size: 40px 40px;
    }
    
    .items-count {
      margin-top: 0px;
      margin-bottom: 0px;
    }
    
    .count {
      color: #a94442;
      padding: 1px;
    }
    
    .items-count p {
      padding-bottom: 5px;
      margin: 0;
      text-transform: uppercase;
      font-weight: 700;
      text-align: center;
      font-family: "DIN Next", Arial, sans-serif;
    }
    
    .progressbar {
      position: relative;
      display: block;
      background-color: #ca0000;
      border: 1px solid #ddd;
      margin-bottom: 15px;
      box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
    }
    
    .progressbar > div {
      background-color: #ca0000;
      width: 0;
      margin-bottom: 0;
      height: 15px;
    }
    
    .progressbar > div.less-than-ten {
      background-color: #ca0000 !important;
    }
    
    #clock-ticker {
      display: block;
      margin-bottom: 15px;
    }
    
    #clock-ticker .block {
      position: relative;
      color: #000;
      font-weight: bold;
      float: left;
      text-align: center;
      width: 25%;
    }
    
    #clock-ticker .block .flip-top {
      width: 88px;
      height: 39px;
      line-height: 40px;
      font-size: 40px;
      text-align: center;
    }
    
    #clock-ticker .block .label, span.flip-top {
      color: #000;
      font-weight: bold;
      text-align: center;
      font-size: 14px;
      text-transform: uppercase;
      width: 88px;
      line-height: 25px;
      font-family: "Open Sans", Arial, sans-serif;
    }
    
    .progressbar div {
      border-radius: 20px;
    }
    
    #progress_bar div {
      border-radius: 20px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="progress_bar"></div>
    <span id="numdays"></span> days
    <span id="numhours"></span> Hours
    <span id="nummins"></span> Minutes
    <span id="numsecs"></span> Seconds
    Login or Signup to reply.
  2. I would create something like:

    //<![CDATA[
    /* js/external.js */
    let doc, html, bod, I, SessionCounter; // for use on other loads
    addEventListener('load', ()=>{
    doc = document; html = doc.documentElement; bod = doc.body;
    I = id=>doc.getElementById(id);
    SessionCounter = function(init = 0, inc = 1, dec = 1){
      if(sessionStorage.count === undefined){
        sessionStorage.count = init;
      }
      this.count = +sessionStorage.count;
      this.inc = (by = inc)=>{
        this.count += by; sessionStorage.count = this.count;
        return this.count;
      }
      this.dec = (by = dec)=>{
        this.count -= by; sessionStorage.count = this.count;
        return this.count;
      }
    }
    // you can put the following on another page using a load Event - besides the end load
    const dec = I('dec'), test = I('test'), inc = I('inc');
    sc = new SessionCounter;
    test.textContent = sc.count;
    dec.onclick = ()=>{
      if(sc.count > 0)test.textContent = sc.dec();
    }
    inc.onclick = ()=>{
      test.textContent = sc.inc();
    }
    }); // end load
    //]]>
    /* css/external.css */
    *{
      box-sizing:border-box; padding:0; margin:0;
    }
    html,body{
      width:100%; height:100%; background:#ccc;
    }
    .main{
      padding:10px;
    }
    #inc,#dec{
      width:20px;
    }
    #test{
      display:inline-block; width:70px; background:#fff; text-align:center;
    }
    <!DOCTYPE html>
    <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
      <head>
        <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
        <title>Title Here</title>
        <link type='text/css' rel='stylesheet' href='css/external.css' />
        <script src='js/external.js'></script>
      </head>
    <body>
      <div class='main'>
        <div>
          <input id='dec' type='button' value='-' />
          <div id='test'></div>
          <input id='inc' type='button' value='+' />
        </div>
      </div>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search