JavaScript para crear un contador descendente

 Hola en la publicación de hoy les comparó como podemos hacer un cont down o contador descendente para algún evento importante, por ejemplo yo lo voy a poner para la llegada del segundo aniversario de este blog 😋 que es el 27 de abril.

Entonces para hacer un contador necesitamos una variable para la fecha objetivo, otro el dato de fecha actual, utilizar la función Math para hacer la resta y preparar nuestra página vamos a utilizar JavaScript para hacer la función 


    <script>

    var varobjetivo = new Date("April 27, 2021 00:00:002").getTime();

    var contdown = setInterval(function() {

    var now = new Date().getTime();

    var timeleft = varobjetivo - now;

    var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));

    var hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

    var minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));

    var seconds = Math.floor((timeleft % (1000 * 60)) / 1000);

        

    document.getElementById("dias").innerHTML = days + "d "

    document.getElementById("houras").innerHTML = hours + "h " 

    document.getElementById("mins").innerHTML = minutes + "m " 

    document.getElementById("secs").innerHTML = seconds + "s " 

        

    if (timeleft < 0) {

        clearInterval(myfunc);

        document.getElementById("dias").innerHTML = ""

        document.getElementById("houras").innerHTML = "" 

        document.getElementById("mins").innerHTML = ""

        document.getElementById("secs").innerHTML = ""

 document.getElementById("end").innerHTML = "¡¡Feliz Aniversario ProgramacionParatodos.com!!";

    }

    }, 1000);

    </script>

En este ejemplo utilice un poco de CSS para agregar formato a las letras y agregamos una imagen de fondo, CSS es para poder generar estilos de formatos en nuestras páginas WEB y hacerlas más bonitas. 



<style>
body {
   background-image: url("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6MJHt5NjpmpsuNaEU68hg2Oei58tfiuXPMWzpV5RhbuZsRxCjkyr45p_lsvtMhMWn5fj17yhVjq7UffEDLTCJueJTwQKG6H7swKE1SSbCpdxKPDGvpNCsuP-rfx6XyISbeSdg2zwi1dQ/s320/Second.png");
   background-repeat: no-repeat;
   background-position: 25% 100%;
}
center {
   text-align: center;
  font-size: 40px;
  color: #FE7F88;
}
</style>

Código de la página

<!DOCTYPE HTML>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1">

<style>

body {

   background-image: url("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6MJHt5NjpmpsuNaEU68hg2Oei58tfiuXPMWzpV5RhbuZsRxCjkyr45p_lsvtMhMWn5fj17yhVjq7UffEDLTCJueJTwQKG6H7swKE1SSbCpdxKPDGvpNCsuP-rfx6XyISbeSdg2zwi1dQ/s320/Second.png");

   background-repeat: no-repeat;

   background-position: 25% 100%;

}

center {

   text-align: center;

  font-size: 40px;

  color: #FE7F88;

}

</style>

</head>

<body>

    <center> Faltan solo  </center>

    <center id="dias"></center>

    <center id="houras"></center>

    <center id="mins"></center>

    <center id="secs"></center>

    <h2 id="end"></h2>

    <script>

    

    var varobjetivo = new Date("April 27, 2021 00:00:002").getTime();


    

    var contdown = setInterval(function() {


    var now = new Date().getTime();

    var timeleft = varobjetivo - now;

        

    // Calculating the days, hours, minutes and seconds left

    var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));

    var hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

    var minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));

    var seconds = Math.floor((timeleft % (1000 * 60)) / 1000);

        

    // Result is output to the specific element

    document.getElementById("days").innerHTML = days + "d "

    document.getElementById("hours").innerHTML = hours + "h " 

    document.getElementById("mins").innerHTML = minutes + "m " 

    document.getElementById("secs").innerHTML = seconds + "s " 

        

    // Display the message when countdown is over

    if (timeleft < 0) {

        clearInterval(myfunc);

        document.getElementById("days").innerHTML = ""

        document.getElementById("hours").innerHTML = "" 

        document.getElementById("mins").innerHTML = ""

        document.getElementById("secs").innerHTML = ""

 document.getElementById("end").innerHTML = "¡¡Feliz Aniversario ProgramacionParatodos.com!!";

    }

    </script>

</body>

</html>


La página se ve de la siguiente forma

La liga es https://ejemploprogramacionparatodos.000webhostapp.com/contadordescente.html

Otra versión pude ser para el cumpleaños de algún familiar, amig@, persona especial, etc..



https://ejemploprogramacionparatodos.000webhostapp.com/cuantosdiasfaltanparamicumpleanosd.html

Si quisieran pueden adaptar la pagina para que lea un dato de entrada para la fecha y sobre ese haga el contador, modificar el formato. Para hacer la pagina solo utilice un editor de Texto e ingresar el código. 


No olvides compartirnos y seguirnos en este blog o en Facebook.

Comentarios

Entradas más populares de este blog

Ejemplo Macro en Word

Macro de Excel para abrir archivo csv

Graficar funciones en Python con dataframes