QAds
Nokia N97 3G, 5 MP Camera, A-GPS, 32 GB, MicroSD Slot
$374.99
Motorola A1200 MING Smartphone
$112.49
Apple iPad 16gb Wi-Fi 3G
$578.62
Apple iPod nano 8 GB Pembe
$87.91
:: HOME JavaScript Count Down and Watch
 
Count Down and Watch

If we want to write countdown with JavaScript you need to know about data, time and math methods. Lets write a coundown script.

 

At first we need to run our script at the start of page and repeat it every second.

 

<body onLoad = "setInterval('countdown()',1000)">

<div id="countdown"></div>

 

onLoad event runs our countdown function at start and setInterval runs it every second. Then we need to define where to show countdown info. Here we need to use DIV.

 

Now lets write our function.

 

<script type="text/JavaScript">

Function countdown() {

newYear = new Date("January 1, 2007");

var today = new Date();

nextYear = today .getFullYear() + 1;

newYear.setFullYear(nextYear);

 

days = (newYear - today )/(1000*60*60*24);

 

var hours = (days - Math.floor(days))*24;

var minutes = (hours - Math.floor(hours))*60;

var seconds = (minutes - Math.floor(minutes))*60;

 

Document.getElementById('countdown').innerHTML=  Math.floor(days) + ' days, ' +  Math.floor(hours) + ' hours, ' +  Math.floor(minutes) + ' minutes, ' +  Math.floor(seconds) + ' seconds to new year';

 

}

</script>

 

At first we determine which date will we count down and then we get today date. We get today's date year and add 1 to know next year and we set new year data year with this next year value. Then we gets how many days, hours, minutes and seconds left and with setInterval, we runs this function every second and write value to our div section. That’s all.

 

If want to count down or write and watch:

 

<script type="text/JavaScript">

Function watch() {

var today = new Date();

thisDate = today .getDate();

thisMonth = today .getMonth()+1;

thisYear = today .getFullYear();

 

thisSecond = today .getSeconds();

thisMinute = today .getMinutes();

thisHour = today .getHours();

 

var ampm = (thisHour<12) ? " am " : " pm ";

thisHour = (thisHour > 12) ? thisHour-12 : thisHour;

thisHour = (thisHour == 0) ? 12 : thisHour;

 

thisMinute = thisMinute < 10 ? "0" + thisMinute : thisMinute;

thisSecond = thisSecond < 10 ? "0" + thisSecond : thisSecond;

 

Document.getElementById('watch').innerHTML= thisMonth + "/" + thisDate + "/" + this year + ' ' + thisHour + ":" + thisMinute + ":" + thisSecond + ampm;

 

}

</script>

 

<body onLoad = "setInterval('watch()',1000)">

<div id="watch"></div>