Thursday, January 26, 2012

JavaScript Code For a Countdown From 10 to 0

Countdown with JavaScript.
Image: Danilo Rizzuti/FreeDigitalPhotos.net
Adding a countdown timer to a Web page is a useful function, particularly if the page contains a timed redirect to another page or resource on your website.

JavaScript code libraries include numerous scripts for counting down to a specific date, but scripts that run a simple Nasa-style countdown from "10" to "0" can be harder to find.

To implement a 10-second countdown timer that displays a numeric “10” to “0” countdown on a Web page, add two snippets of JavaScript code to the HTML design code for the page.

Step-by-Step Guide For a JavaScript Countdown From 10 to 0

Open the Web page on which you want to add the countdown timer display in your usual Web design program, HTML editor application or the Microsoft Notepad plain text editor.

Scroll to the Web page’s header section, contained between the “<head>” and “</head>” tags at the top of the page.

Paste the following functional JavaScript function code before the “</head>” tag:

<script language="JavaScript">
<!--
var secondsleft = 13;
var finishedtext = ":00"
end = new Date();
end.setSeconds(end.getSeconds()+secondsleft);
function cd(){
now = new Date();
diff = end - now;
diff = new Date(diff);
var sec = diff.getSeconds();
if (sec < 10){
sec = "0" + sec;
}
if(now >= end){
clearTimeout(timerID);
document.getElementById("cdtime").innerHTML = finishedtext;
}
else{
document.getElementById("cdtime").innerHTML = ":" + sec;
}
timerID = setTimeout("cd()", 10);
}
window.onload = cd;
//-->
</script>


Change the ":00" text in the fifth line of the above code to your own custom message that displays on the page when the 10-second countdown reaches “0.”

Scroll to the body section of the Web page between the “<body>” and “</body>” tags. This section of the page contains the content that displays on the page.

Paste the following JavaScript code at your preferred display position for the countdown timer:
<span id="cdtime">loading ...</span>

Change the “loading countdown ...” text to your own custom message that displays immediately before the page loads and displays the countdown timer. 

Save the Web page and upload it to your website’s hosting server in the usual way.

No comments:

Post a Comment