How I made a COUTDOWN TIMER using HTML, CSS and JavaScript

ยท

6 min read

How I made a COUTDOWN TIMER using HTML, CSS and JavaScript

Hey, You awesome human ๐Ÿ‘‹,

Introduction

In this tutorial, we are going to see how we can build a countdown timer using HTML, CSS and JavaScript.

The countdown timer will refresh itself every second (no need for the user to reset the page). Just specify the date and you have a countdown to that event with a beautiful background ready to use. Our JavaScript program then takes care of all the necessary calculations to produce the countdown.

Below is a live preview of the completed project:


Setting Up the Project

For this project, we will use the VS Code. If you have not installed the Visual Studio Code yet, then click on the link below for download and installation according to your operating system specifications:

Visual Studio Code

For project setup, start by creating a new project folder in VS Code, and inside that project folder, create three empty new files of HTML (index.html), CSS (style.css) and JavaScript (script.js). The Html file is the entry point for our website and contains the HTML code. CSS contains the styling part of our web project and JavaScript contains various functionalities for proper functioning of our web app.


Analysis of the project

screely-1648637763716.png

A we can see from the screenshot above the page contains a heading element with 4 div element for days, hours, minutes and seconds all of which can be enclosed inside a single outer div element.


Let's see the structuring part starting with HTML later we will see the CSS applied to each HTML element


HTML

  • Get the HTML boilerplate

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

</body>
</html>

This boilerplate can be easily accessed by typing ! on the first line of the HTML file and pressing tab/enter key.

Change the title from document to CountDown Timer


  • Linking CSS and JavaScript file to the markup

<link rel="stylesheet" href="style.css">
<script src="script.js" defer></script>

The defer attribute is a Boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).


  • Adding favicon to the page

    Favicon is one of the most import aspect of any webpage. websites without a favicon looks kinda dull to the end user.
<link rel="shortcut icon"
        href="https://www.pikpng.com/pngl/b/49-495886_png-file-countdown-timer-icon-png-clipart.png"
        type="image/x-icon">

Favicon link


  • Inside body Tag

    body tag contains a heading and 4 div element, which are enclosed inside a outer div box along with required class and id name.
<h1>My Next BirthDay</h1>
    <div class="countdown-container">
        <div class="countdown-el days-c">
            <p class="big-text" id="days">0</p>
            <span>Days</span>
        </div>
        <div class="countdown-el hours-c">
            <p class="big-text" id="hours">0</p>
            <span>Hours</span>
        </div>
        <div class="countdown-el mins-c">
            <p class="big-text" id="minutes">0</p>
            <span>Minutes</span>
        </div>
        <div class="countdown-el sec-c">
            <p class="big-text" id="seconds">0</p>
            <span>Seconds</span>
        </div>
    </div>

  • Entire HTML file at a glance

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CountDown Timer</title>
    <link rel="shortcut icon"
        href="https://www.pikpng.com/pngl/b/49-495886_png-file-countdown-timer-icon-png-clipart.png"
        type="image/x-icon">
    <link rel="stylesheet" href="style.css">
    <script src="script.js" defer></script>
</head>

<body>
    <h1>My Next BirthDay</h1>
    <div class="countdown-container">
        <div class="countdown-el days-c">
            <p class="big-text" id="days">0</p>
            <span>Days</span>
        </div>
        <div class="countdown-el hours-c">
            <p class="big-text" id="hours">0</p>
            <span>Hours</span>
        </div>
        <div class="countdown-el mins-c">
            <p class="big-text" id="minutes">0</p>
            <span>Minutes</span>
        </div>
        <div class="countdown-el sec-c">
            <p class="big-text" id="seconds">0</p>
            <span>Seconds</span>
        </div>
    </div>
</body>

</html>

CSS

  • Adding required styling

    I target the element by class name in CSS and by id name in script.
* {
    box-sizing: border-box;
}

body {
    background-image: url("./snow.jpg");
    min-height: 100vh;
    background-size: cover;
    background-position: center center;
    font-family: "Cascadia Code", sans-serif;
    margin: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}

h1 {
    font-weight: normal;
    font-size: 4rem;
    margin-top: 5rem;
    align-items: center;
    justify-content: center;
}

.countdown-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
}

.big-text {
    font-size: 6rem;
    line-height: 1;
    font-weight: bold;
    margin: 0 2rem;
}

.countdown-el {
    text-align: center;
}

.countdown-el span {
    font-size: 1.3rem;
}

That's conclude the whole styling part. Now, without any further ado, Let's jump right into JavaScript.


JavaScript

  • Target all the element with the help of id

    const daysEl = document.getElementById("days");
    const hoursEl = document.getElementById("hours");
    const minsEl = document.getElementById("minutes");
    const secondsEl = document.getElementById("seconds");
    

  • Set the date

    Set the date till which you want the timer, Just here for example I have set it as my next birthday.
const newDate = "7 Dec 2022";

Note: You can choose any date, just make sure you follow the date format.


  • Function for countdown

    Let's have a function for countdown which will be called once initially, and after that it will be called after every 1 second.
function countdown() {
    const newYearsDate = new Date(newDate);
    const currentDate = new Date();
    // * console.log(newYearsDate - currentDate);
    const totalSeconds = (newYearsDate - currentDate) / 1000;
    const days = Math.floor(totalSeconds / 60 / 60 / 24);
    const hours = Math.floor(totalSeconds / 60 / 60) % 24;
    const minutes = Math.floor(totalSeconds / 60) % 60;
    const seconds = Math.floor(totalSeconds % 60);
    // * console.log(days, hours, minutes, seconds);

    daysEl.innerHTML = formatTime(days);
    hoursEl.innerHTML = formatTime(hours);
    minsEl.innerHTML = formatTime(minutes);
    secondsEl.innerHTML = formatTime(seconds);
}

Note: I am not erasing out extra console.log as it is a good beginner practice to see what's happening in your codebase in your log window.


  • Calling the function every 1 seconds

setInterval(countdown, 1000);

This piece of code calls the countdown function every 1000 milliseconds i.e. 1 second


  • Entire JavaScript file at a glance

const daysEl = document.getElementById("days");
const hoursEl = document.getElementById("hours");
const minsEl = document.getElementById("minutes");
const secondsEl = document.getElementById("seconds");

const newDate = "7 Dec 2022";

function countdown() {
    const newYearsDate = new Date(newDate);
    const currentDate = new Date();
    // * console.log(newYearsDate - currentDate);
    const totalSeconds = (newYearsDate - currentDate) / 1000;
    const days = Math.floor(totalSeconds / 60 / 60 / 24);
    const hours = Math.floor(totalSeconds / 60 / 60) % 24;
    const minutes = Math.floor(totalSeconds / 60) % 60;
    const seconds = Math.floor(totalSeconds % 60);
    // * console.log(days, hours, minutes, seconds);

    daysEl.innerHTML = formatTime(days);
    hoursEl.innerHTML = formatTime(hours);
    minsEl.innerHTML = formatTime(minutes);
    secondsEl.innerHTML = formatTime(seconds);
}

function formatTime(time) {
    return time < 10 ? `0${time}` : time;
}

// * Initial call
countdown();

setInterval(countdown, 1000);

Thank you for reading. If you have come this far, don't forget to react to this blog.


If you โค๏ธ My Content! Connect with me on Twitter (abhinav_jha07)


Show your support by buying me a coffee

Buy Me A Coffee


My other digital presence:


More Content at abhinavjha07.hashnode.dev/


Your feedback is more than welcome

Did you find this article valuable?

Support Abhinav's Blog by becoming a sponsor. Any amount is appreciated!

ย