Monday, October 04, 2010

JavaScript: Count down Timer

This is how creating Count down timer using JavaScript with Julian dates. This code below creates two Julian dates, now and newYear. By subtracting now from newYear we get an integer which represents the difference between the two dates.

Suppose you want to know your birthday in days, hours and minutes etc. This is how you can achieve using JavaScript.

<!-- This span is where the countdown timer will appear -->
<div id='countdown'></div>
<script type="text/javascript">
// Here's our countdown function.
function happyBirthDay() {
var now = new Date();
var newYear = new Date('October 20, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);   
    diff=diff/1000;            
var seconds=Math.floor(diff % 60);
    diff=diff/60;
var minutes=Math.floor(diff % 60);
    diff=diff/60;
var hours=Math.floor(diff % 24);
    diff=diff/24;
var days=Math.floor(diff);
// We'll build a display string instead of doing document.writeln
   var outStr = days + ' days, ' + hours+ ' hours, ' + minutes;
       outStr+= ' minutes, ' + seconds + ' seconds until your birthday!'; 
   // Insert our display string into the countdown span.
   document.getElementById('countdown').innerHTML=outStr;
   // call this function again in exactly 1 second.   
   setTimeout("happyBirthDay()",1000);
}
// call the countdown function (will start the timer)
happyBirthDay();   
</script>

Hope this helps!

No comments:

Post a Comment