Redirect with a Timer
There maybe times that you want to redirect a visitor on your site. In JavaScript, you can use window.location to redirect a user to a different page. You may have seen this used by sites with full page ads, or to redirect users to the site's new domain name. You can add a timer to the script that will allow the page to redirect and the user will not need to click a link or type in the new URL.
<script language="JavaScript" type="text/javascript">
var count =6
var redirect="http://www.code-sucks.com"
function countDown(){
if (count <=0){
window.location = redirect;
}else{
count--;
document.getElementById("timer").innerHTML = "This page will redirect in "+count+" seconds."
setTimeout("countDown()", 1000)
}
}
</script>
Our webpage has moved. Please update your bookmarks for the new site.
<span id="timer">
<script>
countDown();
</script>
</span>
So the script is redirecting the user since the site's domain name has been changed. The first thing the script does is set two variables, one is named count, and the other is named redirect. We see that redirect is set to the URL that we want the user to be redirected to, and count that is set to six. We then see a function called countDown. Inside this function we see an if else statement. It tells us that if count is less than or equal to zero, then we want the window location to be the value or our redirect variable. The else part of the function subtracts one from count, then displays the value of count, along with the sting This page will redirect in seconds. The last part of the else sets a timer with the setTimeout function built into JavaScript. We tell the setTimeout function to run the countDown function every 1000 milisecond, or every second. Below is an example of the code, but without the redirect. If you loaded the page over five seconds ago, then just reload the page to see the example.
iEntry 10th Anniversary
CSS Snippets
JavaScript Snippets