Create a Countdown with JavaScript and jQuery

Below is the code to create a timer countdown using HTML, SASS, ES6 JavaScript and jQuery. The target date is December 31, 2017. Please contact me at maria@mclinteractive.com if you have any questions.

Demo

December 31, 2017 Midnight
Days
Hrs
Mins
Secs
00
00
00
00

Resources

Dependency. The jQuery Library can be included at the bottom of the html document just above the </body>.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Description

We used the Date object to get the current and target dates. In addition, we created a counter to tick the seconds. The styles are provided below.

JavaScript

If you don’t use development tools such as Webpack, compile the ES6 Javascript displayed below with Babel, and place it below the JQuery library.

<script>
(function($) {
    const Countdown = {

        init(el) {

            let self = this;

            self.options = {
                'timeStamp': new Date().getTime(),
                'counter': 0,
                'currentTime':0
            };
            self.setClock(el);

        },

        setClock(el) {

            let self = this;

            let clock = setInterval(function () {
                self.setTime(el);
            }, 1000);

            self.clock = clock;
            self.setTime(el);
        },

        setTime(el) {
            let self = this,
                gapTime,
                daysGap = el.find('.days'),
                hoursGap = el.find('.hours'),
                minutesGap = el.find('.minutes'),
                secondsGap = el.find('.seconds'),
                endTime = new Date(2018, (1 - 1), (1), 0, 0, 0, 0); //12/31/2017 midnight remember Months are zero based. Making the end date the date FOLLOWING the "official" date at midnight. 
            let setSingleDigits = (val) => {
                var formatVal = (val < 10) ? ("0" + val) : val.toString();
                return formatVal;
            };  
            
            endTime = endTime.getTime();

            self.options.currentTime = (self.options.counter === 0) ? self.options.timeStamp : (self.options.currentTime + 1000); 

            gapTime = parseInt(endTime) - parseInt(self.options.currentTime);

            if (gapTime < 0) {

                clearInterval(self.clock); // stop the clock

                $(daysGap).text("00");
                $(hoursGap).text("00");
                $(minutesGap).text("00");
                $(secondsGap).text("00");

            } else {

                let msPerDay = 24 * 60 * 60 * 1000,
                    msPerHour = 60 * 60 * 1000,
                    msPerMinute = 60 * 1000,
                    msPerSecond = 1000,

                    days = setSingleDigits(Math.floor(gapTime / msPerDay)),
                    hours = setSingleDigits(Math.floor((gapTime % msPerDay) / msPerHour)),
                    minutes = setSingleDigits(Math.floor(( gapTime % msPerHour) / msPerMinute)),
                    seconds = setSingleDigits(Math.floor((gapTime % msPerMinute) / msPerSecond));

                $(daysGap).text(days);
                $(hoursGap).text(hours);
                $(minutesGap).text(minutes);
                $(secondsGap).text(seconds);
            }

            self.options.counter = self.options.counter + 1;

        }
    };

    $(function () { // ON DOM READY

        if ($('#countdown').length > 0) {

            $('#countdown').each(function () {
                const countdownObj = $(this);
                Countdown.init(countdownObj);
            });
        }
    });
}(jQuery));
</script>

HTML

Place the HTML displayed below somewhere in your page between the <body> and <\body>.

<section id="countdown">
   <div class="end-date">December 31, 2017 Midnight</div>
   <div class="label-wrapper"><div>Days</div><div>Hrs</div><div>Mins</div><div>Secs</div></div>
   <div class="clock-wrapper"><div class="days">00</div><div class="hours">00</div><div class="minutes">00</div><div class="seconds">00</div></div>
</section>

SASS

Process the SASS displayed below to obtain the CSS, which should be placed somewhere between the <head> and <\head>.

@import url('https://fonts.googleapis.com/css?family=Roboto+Condensed');
$black:#000;
$darkgray: #555;
$gray: #f4f4f4;
$white: #fff;
body { 
    width:100%;
    background:$gray;
    color:$black;
}
#countdown { 
    background-color: $darkgray;
    font-family: 'Roboto Condensed', sans-serif;
    text-align: center;
}
.label-wrapper div, .clock-wrapper div { 
    display:inline-block; 
    width:50px; 
    color:$white;
    text-align:center;
}

About the Author

Maria C. Lima

Maria C. Lima has spent the past 10 years studying web development and becoming a sought-after independent web designer & developer in New York City. She now runs MCL Interactive, her own NYC design and technology firm, where she prides herself in providing creative web solutions for savvy entrepreneurs. She helps bring their vision to life in a beautiful and functional web presence. Her goal is to take care of all the techy stuff so that they can do what they love and work on growing their businesses. You can find her on Twitter (@mclinteractive) or on Facebook (Facebook.com/mclinteractive). Read more

Related posts

You might be interested in the following posts: