DEV Community

loading...
Cover image for Countdown with HTML and JS

Countdown with HTML and JS

Walter Nascimento
Software development | PHP | JavaScript | Database | Open-Source
・2 min read

[Clique aqui para ler em português]

How about knowing how much time is left for a specific date in a very simple way? how much time is left for your birthday or holiday, see below how fast this project is.

Code

First we will create the interface, we will do something simple, using only HTML.

<h1>Contagem regressiva</h1>
<form name="form_main">
  <label for="numero">Data:</label> 
  <input name='date_end' type="date" onblur="resetCountdown()" />
  <br>
</form>
<div class="container">
  <h1>Contagem regressiva até a data selecionada:</h1>
  <ul>
    <li><span id="days"></span>days</li>
    <li><span id="hours"></span>Hours</li>
    <li><span id="minutes"></span>Minutes</li>
    <li><span id="seconds"></span>Seconds</li>
  </ul>
</div>

In the HTML structure, an input was created to receive the date, and when exiting the input, onblur is activated and calls the resetCountdown() function.

const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;

let count_down = new Date('03/03/2025 00:00:00').getTime();
let x = setInterval(() => countDown(), second);

function countDown() {
  let now = new Date(Date.now()).getTime();
  let diff = count_down - now;

  document.getElementById('days').innerText = Math.floor(diff / day);
  document.getElementById('hours').innerText = Math.floor(diff % day / hour);
  document.getElementById('minutes').innerText = Math.floor(diff % hour / minute);
  document.getElementById('seconds').innerText = Math.floor(diff % minute / second);
}

function resetCountdown() {
  clearInterval(x);
  let date_end = document.form_main.date_end.value;
  count_down = new Date(`${date_end} 00:00:00`).getTime();
  x = setInterval(() => countDown(), second);
}

Here we have the countdown() function, which starts when we load the page, and after it we have the resetCountdown() function, which is activated as soon as we fill the date and the input loses focus.

ready as simple as that.

Demo

See the complete project working below.

Youtube

If you prefer to watch, I see the development on youtube (video in PT-BR).


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you! 😊😊

Discussion (0)