Archive for the ‘Javascript’ Category

Javascript countdown then redirect

Wednesday, October 24th, 2007

Today I needed to write a simple piece of javascript that counts down and then submits a form. This could easily be adapted to count down before redirecting to another website. Below is sample code that you can add to any page, which counts down from 10 and then displays a message to the user. The countdown is displayed on the page.

Add this to the <head> section of the page:
<script>
<!--
function startCount() {
var countfrom=10 // this controls what number to start counting from
var countnow=document.getElementById('mySeconds').innerHTML=countfrom+1
countAction(countnow)
}

function countAction(countnow) {
if (countnow!=1) {
countnow-=1
document.getElementById(’mySeconds’).innerHTML=countnow;
} else {
alert(’BOOM!’);
return
}
setTimeout(”countAction(”+countnow+”)”,1000)
}
//–>
</script>

Add this to the <body> section:
<p>This page will self destruct in <span id="mySeconds">10</span> seconds...</p>

In order for the counter to start you will need to call the function startCount. You can do this when the page loads by adding onload="javascript:startCount();" to the <body> like below:
<body onload="javascript:startCount();">

Example: Click here to see this in action.