-1

I'm trying to create a 24 hour sale time for a website. I've figured out how to do this for a daily timer that starts at midnight by taking the current time but I need to be more flexible with this and be able to start it at a random time of the day. The code I've currently got:

  <div id="countdown_hours"></div>
  <script>
  setInterval(function time(){
  var d = new Date();
  var hours = 24 - d.getHours();
  var minutes = 60 - d.getMinutes();
  if((minutes + '').length == 1){
    minutes = '0' + minutes;
  }
  var seconds = 60 - d.getSeconds();
  if((seconds + '').length == 1){
        seconds = '0' + seconds;
  }
  document.getElementById("countdown_hours").innerHTML =
             '<div class="clockcontainer">'
              + '<p>Promo</p>'
              + '<div class="clock">'
              + '<div class="count"><span>'
              + hours
              + '</span> <label> Hours</label> </div>'
              + '<div class="count"><span>'
              + minutes
              + '</span> <label> Minutes</label> </div>'
              + '<div class="count"><span>'
              + seconds
              +'</span> <label> Seconds</label> </div>'
              + '</div>'
              + '</div>';
}, 1000);
  </script>

So I guess I need to set a variable to my countdown time so var time = 24 for example and then count down from this var time in hours, minutes and seconds. Can anybody point me in the right direction of how to achieve this?

MariaL
  • 1,112
  • 2
  • 16
  • 41

3 Answers3

0

you can use jQuery Countdown

 var newYear = new Date(); 
newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1); 
$('#defaultCountdown').countdown({until: newYear}); 
Vitaly Menchikovsky
  • 7,684
  • 17
  • 57
  • 89
0

You could do something like this:

// A countdown object
const CountDown = function (target) {
    const endTime = new Date(target);

    // Return a date object with the time left
    this.getTime = () => new Date(endTime - Date.now());
}

// This simply a method of setting the date to 24 hours
// See https://stackoverflow.com/a/3674550/3533202
const tomorrow = new Date();
tomorrow.setDate(
    new Date().getDate() + 1
);

// Initialise the countdown object
const countdown = new CountDown(tomorrow);

// Get the element you want to change
const elem = document.getElementById("countdown_hours");

setInterval(function (elem) {
    const timeLeft = countdown.getTime();

    // Get the time left in numerical format
    const hours = timeLeft.getHours();
    const minutes = timeLeft.getMinutes();
    const seconds = timeLeft.getSeconds();

    // Now populate your element
    // This is a template literal, see:
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
    console.log(`
    <div class="clockcontainer">
        <p>Promo</p>
        <div class="clock">
            <div class="count">
                <span>${hours}</span>
                <label> Hours</label>
            </div>
            <div class="count">
                <span>${minutes}</span>
                <label> Minutes</label>
            </div>
            <div class="count">
                <span>${seconds}</span>
                <label> Seconds</label>
            </div>
        </div>
    </div>`)
}, 1000, elem)
scagood
  • 784
  • 4
  • 11
0

You could mark all your countdowns by some specific class and pass unix timestamp for countdown in data attribute.

I strongly recommend using moment.js library for time manipulation in javascript (it has rich API, it's build on top of default Date class for compatibility, works almost everywhere and supports text localizations).

Simple example:

function countdown(el, interval) {
  const end = moment.unix(el.dataset.end);
  const dur = moment.duration(end.diff(moment()));
  let html = ''
  if(dur.hours() > 0) {
   const hours = Math.floor(dur.asHours(true));
   html += hours + ' ' + plural(hours, 'hour') + ', ';
  }
  if(dur.minutes() > 0) {
   html += dur.minutes() + ' ' + plural(dur.minutes(), 'minute') + ', ';
  }
  if(dur.seconds() > 0) {
   html += dur.seconds() + ' ' + plural(dur.seconds(), 'second') + ', ';
  }
  html = html.slice(0, -2);
  
  if(dur <= 0) {
   clearInterval(interval);
   html = 'Now';
  }
  el.innerHTML = html;
}

function plural(n, word) {
 return word + ((n === 1) ? '' : 's');
}

const elements = document.getElementsByClassName('countdown');
Array.prototype.forEach.call(elements, function (el) {
 const interval = setInterval(function() {
    countdown(el, interval);
  }, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<div class="countdown" data-end="1519302600"></div>
<div class="countdown" data-end="1519776030"></div>

jsFiddle link