flipdown icon indicating copy to clipboard operation
flipdown copied to clipboard

Persist across Browser sessions

Open billiemead opened this issue 1 year ago • 4 comments

I set up a Flipdown countdown timer to calculate how much time between when the CMS page is published and Midnight EST (when a callback changes a CSS class that removes an overlay).

    var now = new Date();
    var night = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() + 1, // the next day, ...
        0, 0, 0 // ...at 00:00:00 hours
    );
    var timeUntilMidnight = night.getTime() - now.getTime();

Now, I'd like to use localStorage to make sure the countdown persists and keeps on ticking!

    // get timer offset (if not found, set to today)
        var now = new Date( localStorage.getItem('countdown-offset') || new Date() );

        // store the offset
        localStorage.setItem('countdown-offset', offset);

But when the count actually starts, wouldn't I want to use something like onUpdate ? Im actually not sure!

billiemead avatar Nov 14 '24 12:11 billiemead

I'm trying to understand your use case. FlipDown works by using a timestamp of some time in the future. If you know when your timer is due to end and store the original end-time in LocalStorage, when the user re-visits your page and the timestamp is retrieved from LocalStorage, the end time will still be the same and the counter will appear to have kept ticking while the user was away.

Did I misunderstand your use case?

PButcher avatar Nov 15 '24 09:11 PButcher

Thank so much for getting back to me. The issue is that the counter is starting over on each page refresh.. did I set it up wrong i wonder? If its any help here's a link to our staging environment: https://mcstaging.mishimoto.com/mishimoto-black-friday

billiemead avatar Nov 18 '24 06:11 billiemead

@PButcher And yes Peter, that was what I was trying to do with Local storage.

billiemead avatar Nov 18 '24 15:11 billiemead

Here's a minimal example of what you might need to set up: https://codepen.io/pbutcher/pen/OJKYmWx?editors=0010

  const endTime = window.localStorage.getItem('endTime');
  let timeUntilMidnight = 0;
  
  if(!endTime) { 
    let nextMidnight = new Date();
    nextMidnight.setHours(24, 0, 0, 0);
    timeUntilMidnight = Math.floor(nextMidnight.getTime() / 1000);

    window.localStorage.setItem('endTime', timeUntilMidnight);
  }

  // Set up FlipDown
  var flipdown = new FlipDown(endTime !== null ? parseInt(endTime) : timeUntilMidnight)

This will check to see if there's already an endTime in LocalStorage before either using that value or setting it to the next midnight. This isn't based on the next midnight from whenever your CMS generated the page though, you'll need to add in the data source for that.

PButcher avatar Nov 19 '24 01:11 PButcher