Creating a Countdown Timer with JavaScript

Prerequisites: Basic understanding of HTML, CSS, and JavaScript.

Required Tools: A text editor (like Sublime Text, Atom, or Visual Studio Code) and a modern web browser.

Here’s how to create a “Coming Soon” page with a countdown timer.

Step 1: Create the HTML structure

First, let’s create the HTML structure for our countdown timer. We’ll have separate div elements for days, hours, minutes, and seconds.

<!DOCTYPE html>
<html>
<head>
    <title>Coming Soon</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <h1>Coming Soon!</h1>
    <div id="countdown">
        <div id="days"></div>
        <div id="hours"></div>
        <div id="minutes"></div>
        <div id="seconds"></div>
    </div>
    <script src="countdown.js"></script>
</body>
</html>

Step 2: Add some CSS styling

Next, we’ll add some CSS to make our countdown look fancy.

body {
    background-color: #f4f4f4;
    font-family: Arial, sans-serif;
    text-align: center;
    padding: 50px;
}

#countdown {
    display: flex;
    justify-content: center;
    gap: 20px;
}

#countdown > div {
    background-color: #333;
    color: #fff;
    padding: 20px;
    border-radius: 10px;
}

Step 3: Create the JavaScript countdown

Finally, we’ll create a JavaScript file that updates the countdown every second.

// Set the date we're counting down to
var countDownDate = new Date("Dec 31, 2023 23:59:59").getTime();

// Update the count down every 1 second
var countdownFunction = setInterval(function() {

    // Get today's date and time
    var now = new Date().getTime();

    // Find the distance between now and the countdown date
    var distance = countDownDate - now;

    // Calculate time for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Display the result in the respective element
    document.getElementById("days").innerHTML = days + "d ";
    document.getElementById("hours").innerHTML = hours + "h ";
    document.getElementById("minutes").innerHTML = minutes + "m ";
    document.getElementById("seconds").innerHTML = seconds + "s ";

    // If the countdown is finished, display some text 
    if (distance < 0) {
        clearInterval(countdownFunction);
        document.getElementById("countdown").innerHTML = "EXPIRED";
    }
}, 1000);

Now you can open your HTML file in a web browser and see the countdown in action. Please note that the countdown date is set to “Dec 31, 2023 23:59:59”. You can change this to your desired date. The countdown timer will update every second until it reaches the target date. After that, it will display