Javascript Counter

March 23, 2016
Category: TIL
Tags: Javascript

Today I learned:

Javascript Counter

The results:

00

days

00

hours

00

minutes

00

seconds

The javascript, which counts the time since a certain date:

document.addEventListener("DOMContentLoaded", function(event) {
  // Month,Day,Year,Hour,Minute,Second
  upTime('Nov,10,2015,00:00:00'); 
});
function upTime(countTo) {
  now = new Date();
  countTo = new Date(countTo);
  difference = (now-countTo);

  days=Math.floor(difference/(60*60*1000*24)*1);
  hours=Math.floor((difference%(60*60*1000*24))/(60*60*1000)*1);
  mins=Math.floor(((difference%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
  secs=Math.floor((((difference%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);

  document.getElementById('days').firstChild.nodeValue = days;
  document.getElementById('hours').firstChild.nodeValue = hours;
  document.getElementById('minutes').firstChild.nodeValue = mins;
  document.getElementById('seconds').firstChild.nodeValue = secs;

  clearTimeout(upTime.to);
  upTime.to=setTimeout(function(){ upTime(countTo); },1000);
}

The elements it targets:

<div id="countup">
	<div class="part">
	  <p id="days">00</p>
	  <div class="label"><p class="timeRefDays">days</p></div>
	</div>
	<div class="part">
	  <p id="hours">00</p>
	  <div class="label"><p class="timeRefHours">hours</p></div>
	</div>
	<div class="part">
	  <p id="minutes">00</p>
	  <div class="label"><p class="timeRefMinutes">minutes</p></div>
	</div>
	<div class="part">
	  <p id="seconds">00</p>
	 <div class="label"><p class="timeRefSeconds">seconds</p></div>
	</div>
</div>

And the styles to display it:

#countup {
	margin-left: auto;
	margin-right: auto;
	text-align: center;
    font-family: "Lato",Helvetica,Arial,sans-serif;
}
#countup p {
	display: inline-block;
	padding: 0px;
	margin: 0;
	font-size:100px;
	line-height: 100px;
	text-align: center;
}
#countup #seconds, #countup .timeRefSeconds {
	color:red;
}

#countup .part {
	display: inline-block;
	text-align: center;
	width: 23%;
}
#countup .label p{
	font-size: 30px;
}

@media only screen and (max-width: 960px) {

	#countup p {
		font-size: 60px;
		line-height: 60px;
	}
	#countup .label p{
		font-size: 20px;
	}

}

@media only screen and (max-width: 500px) {

	#countup p {
		font-size: 45px;
		line-height: 45px;
	}
	#countup .label p{
		font-size: 16px;
	}
}

Find this post useful?

Buy me a coffeeBuy me a coffee