New year count down for your website in pure/ vanilla java-script.

NEW YEAR COUNT DOWN FOR YOUR WEBSITENew year count down for your website

A new year count down would be a good decoration for your website as a new year is approaching.
My friend was searching for a template for this. The template does the job but how do they do it?
In this article we try to create one in simple pure java-script.

Lets start with our basic html template.

<div id=countdown>
<div id=day class=box>
<div id=hrs class=box>
<div id=min class=box>
<div id=sec class=box>

Now lets style it up

.box {
    background: black;
    color: white;
    display: inline - block;
    width: 75 px;
    height: 50 px;
    font - family: Gill Sans,
    Gill Sans MT,
    sans - serif;
    font - size: xx - large;
    box - sizing: border - box;
    padding - top: 5 px;
    border - radius: 25 px;
    text - align: center;

Now lets go into the fun java-script part

Lets start by declaring our variables

var time_then = new Date("January 1, 2015 00:00:00");
time_then = time_then.valueOf() / 1000;
var looper, time_now, day, hrs, min, sec,
    divsec = document.getElementById('sec'),
    divmin = document.getElementById('min'),
    divhrs = document.getElementById('hrs'),
    divday = document.getElementById('day');

time_then is our future time in this case NEW YEAR date.

The .valueOf() function returns time in milliseconds which we convert to second by dividing by 1000,

Lets get into our function

function change() {
    time_now = new Date();
    time_now = time_now.valueOf() / 1000;
    day = (time_then - time_now) / (3600 * 24);
    hrs = (day - parseInt(day)) * 24;
    min = (hrs - parseInt(hrs)) * 60;
    sec = (min - parseInt(min)) * 60;
    divsec.innerHTML = parseInt(sec);
    divmin.innerHTML = parseInt(min);
    divhrs.innerHTML = parseInt(hrs);
    divday.innerHTML = parseInt(day);
    if (parseInt(sec) === 0 && parseInt(min) === 0 && parseInt(hrs) === 0 && parseInt(day) === 0) {
        //do something awesome
looper = setInterval(function() {
}, 100);

So we have a looping function here which counts down and stops when everything is 0 .

Here is a list of what happens inside the function in each loop

  • Store current time in time_now .
  • Convert time_now to seconds.
  • Days left is  total seconds left divided by 60*60*24 .
  • Hours left is value after the decimal point of days left multiplied by 24.
  • Minutes left is value after the decimal point of hours left multiplied by 60.
  • Seconds left is the value after the decimal point of minutes left multiplied by 60.
  • Print the integer values of results found out into their respective containers.
  • If everything is zero exit the loop and do something awesome.

Is there a short term for value after the decimal point?

Anyway here is our final output

Hope you will like this article “New year count down for your website

We will be happy to hear your thoughts

      Leave a reply