1

I'm working on a countdown timer and I have this piece of code right now. I took it from a different post and modified it a bit. I probably don't have to explain how the script works but here is the way I want it to work:

  1. Set a startdate and enddate in the html attributes.
  2. Pass that data into two variables 'dataStart' and 'dataEnd'.
  3. Use the 'dataStart' as startdate and use the 'dataEnd' as enddate.
  4. Countdown from startdate to enddate like this:
  5. If the startdate is in the future, don't start the countdown yet but let it start as soon as the startdate = the currentdate.
  6. If the startdate is in the past, start the countdown but display the amount of days, hours, minutes and seconds left from the currentdate to the enddate.

    var dataEnd = document.getElementById('countdown').getAttribute("data-end");
    var dataStart = document.getElementById('countdown').getAttribute("data-start");
    
    var _second = 1000;
    var _minute = _second * 60;
    var _hour = _minute * 60;
    var _day = _hour * 24;
    var timer;
    var tiles = document.getElementById('tiles');
    var tilesClass = document.getElementById('tiles').classList;
    var countLabel = document.getElementById('countdown-label');
    var countDiv = document.getElementById('countdown');
    
    function showRemaining() {
    var end = new Date(dataEnd);
    var start = new Date();
    var distance = end - start;
    
    if (distance < 0) {
    clearInterval(timer);
    // Replaces the countdown tiles with '---' & the label with 'SALE IS OVER'.
    tiles.innerHTML = '---';
    countLabel.innerHTML ='SALE IS OVER!';
    // Sets display to none, so when the countdown is finished it will NOT be visible anymore.
    countDiv.style.display = 'none';
    return;
    } if (distance < _hour ) {
    // Removes the Orange background and adds the Red background.
    tilesClass.remove('color-half');
    tilesClass.add('color-empty');
    countLabel.innerHTML ='HURRY! SALE ENDS IN:';
    } else {
    // Sets display to block, so when the countdown is NOT finished it  will be visible.
    countDiv.style.display = 'block';
    }
    
    var days = pad(Math.floor(distance / _day));
    var hours = pad(Math.floor((distance % _day) / _hour));
    var minutes = pad(Math.floor((distance % _hour) / _minute));
    var seconds = pad(Math.floor((distance % _minute) / _second));
    
    tiles.innerHTML = days + ':';
    tiles.innerHTML += hours + ':';
    tiles.innerHTML += minutes + ':';
    tiles.innerHTML += seconds + '';
    }
    
    timer = setInterval(showRemaining, 1000);
    
    function pad(n) {
    return (n < 10 ? '0' : '') + n;
    }
    

I have basic javascript knowledge but can't figure this out myself...

fence
  • 25
  • 2

0 Answers0