Tips for preventing countdown from resetting when you refresh the page

I'm currently using a countdown feature on my Shopify website that is functioning well, except for one issue - whenever the page is refreshed, the countdown resets itself. Can anyone provide guidance on how to solve this problem? Thank you in advance!

Below is the code snippet that I am using:

<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...

Answer №1

To accomplish this task, utilize the power of SessionStorage. Save the count for each day, hour, minute, and second in SessionStorage using the web storage API.

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

Upon reloading the page, retrieve the values stored in sessionStorage. If they are not found, resort to the default values extracted from the Date() function.

You can test the functionality by running the stack snippet provided below. Please note that due to security restrictions, the 'sessionStorage' property cannot be accessed in the stack snippet environment as it requires the 'allow-same-origin' flag.

Therefore, I have added comments to the code and adjusted the if conditions for demonstration in a real environment. In the snippet below, it's:

if (false && sessionStorage)
When implementing this code in your browser, modify these if conditions to: if (sessionStorage) This will demonstrate the retention of the counter value upon page refresh.

... [code snippets and additional instructions continue]

Answer №2

I have developed something similar to the following:

//<![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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The calendar on the Datetimepicker is not appearing in the proper position

I have encountered an issue while using Eonasdan bootstrap datetimepicker in a paramquery grid. Whenever I open the datetimepicker, the calendar appears hidden inside the grid. To tackle this problem, I added the following CSS condition: .dr ...

What are the steps for modifying the JSON data format in AngularJS?

As a newcomer to Angular JS, I am working with the following JSON data: { "CheckList": [ { "UnitClass": "Budget Space", "CheckListCategoryId": 1, "CheckListCategory": "DOORS", "CheckListItemId": 2, "CheckListItem": "Deadbolt, Lockse ...

Challenges with jQuery: Appending strings to a dynamically selected element

Hello everyone, I have a question regarding adding the string 'url(" ")' around my Any assistance you can provide would be greatly appreciated. Thank you! $(function() { $('#list li a').hover( function(){ $("#meow").css( " ...

Error in Highcharts: The property '0' is undefined and cannot be read

Attempting to integrate data from a REST API into HighCharts, but encountering an issue: TypeError: Cannot read property 'series' of undefined. This function retrieves the data from the API: $scope.myData = function(chart) { HighCharts.query ...

Why won't the code for detecting the DEL key in a textarea work on my computer?

I've been trying to detect when a user presses the Delete key and came across this helpful tutorial here The code worked flawlessly on jsfiddle.net, you can check it out here- http://jsfiddle.net. However, when I copied the same code to my local comp ...

Is it possible to modify the CSS of a single class when hovering over a child class of a different and unrelated class?

I am struggling with CSS combinators, especially when dealing with nested div, ul, and li elements. My issue involves changing the CSS of a div with the class "H" when hovering over li elements with the class "G". Since all of this is contained within a s ...

Implementing Image Data in AngularJS: A Guide to Binding Images to IMG Tags

Allow me to explain the problem further. I am retrieving a user's profile picture by calling an API that returns image data, as shown in the screenshot below https://i.stack.imgur.com/t8Jtz.jpg https://i.stack.imgur.com/pxTUS.png The reason I canno ...

Tips for resolving the issue of 'no serverless pages built' during deployment of a Next.js application on Vercel

Recently, I've been encountering the same two errors while trying to deploy my NextJs app: // and will just error later on Error: No serverless pages were built. You can learn more about this error here I'm stuck and unsure of how to resolve bo ...

Changing the color of placeholder text in MUI 5 TextField

Looking to customize the text color and placeholder text color in my MUI TextField component to be green https://i.sstatic.net/NZmsi.png The documentation doesn't provide clear instructions, so I attempted a solution that didn't work: <TextF ...

Is there a way to reference an image in the ROOT/app/assets/images directory prior to precompilation?

My current challenge involves using HTML to display an image before the asset precompilation process, which usually moves all images into the public folder. Whenever I use this code: <img src="Flower.jpg">, it points to the path: <RAILS ROOT>/ ...

Tips for specifying headings for a particular div ID

I'm attempting to customize the font-family of the headings within my header section differently from the headings located elsewhere on the webpage. Unfortunately, I am encountering difficulties in ensuring that this style change only affects the spec ...

Is the Messenger Bot ignoring random users?

I am facing an issue that I need help explaining. The bot works perfectly when I use it from my own Facebook account. However, when I ask others to use it, the bot does not respond to them, even though I have received a green tick on the pages_messaging a ...

Animating components when they first mount in React

I'm attempting to implement an onMount animation in React (and Tailwind if relevant). The code I currently have is as follows: const Component = () => { const [mounted, setMounted] = useState(false) useEffect(() => { setTimeout(( ...

Performing string replacement on an Ajax response prior to adding it to the document

I'm facing an issue when trying to update the response from a jQuery ajax request. I need to replace myPage.aspx with /myfolder/myPage.aspx before adding it to the DOM. Is it possible to achieve this using jQuery or plain Javascript? This is how a pa ...

Ways to make a div adjust to the width of its content

Hello, this is my first time posting a question here. I have found many helpful Java answers in this community before, so I thought I'd give it a try. I did some research beforehand, but please let me know if I have duplicated a question or done anyth ...

The input type file is not correctly inserting an image into the image tag

While I was working on a project, I had a question that got answered but now I need to find a different way to use the solution. I have created a jsFiddle to demonstrate how it currently works. You can view it here: http://jsfiddle.net/TbZzH/4/ However, w ...

SSR with Material UI Drawer encounters issue during webpack production build meltdown

When I attempted to utilize the Material UI SSR example provided by Material-UI (Link), it worked successfully. However, my next step was to integrate the Material-UI Drawer into this example. To do so, I utilized the Persistent drawer example code also pr ...

Cross-Browser Compatibility of CSS

I have noticed that lists styled with the following CSS code appear differently in Internet Explorer 8 and Firefox 4. In IE8, the rounded corners are missing, while FF4 does not change color when hovering over it. Which browser should I trust for accurate ...

Scroll overflow can be hidden

I'm working on a project with a div containing scrollable content, but I'm struggling to get the header to overflow its parent element. It seems that using overflow: scroll is causing the element to have overflow: hidden as well. Any assistance ...

Tips for retrieving the chosen value from an ajax.net ComboBox using javascript

Is there a way to extract the selected value from an ajax.net combobox using JavaScript for client-side validation? What would be the most effective method to achieve this? Thank you. This is how I managed to obtain the value: var combo = $get('ddl ...