Countdown Redirect
There are a number of ways to redirect a browser. Examples: A redirect can be specified in the .htaccess
file. It can be done with PHP. It can be done with JavaScript.
When done with JavaScript, the redirect can happen without notice or it can happen with a visible countdown timer.
This article is about a JavaScript redirect with a visible countdown. The countdown number is decremented every second. (For other redirects already written about at Willmaster.com, type "redirect" in the site's search box.)
The demo page illustrates how this countdown redirect works.
To implement, first put this code into your web page where you want the coundown numbers to publish.
<span id="number-of-seconds-to-go"></span>
The number-of-seconds-to-go
id value is used in the JavaScript (further below). If the id value is changed, the corresponding value in the JavaScript also needs to be changed.
The JavaScript uses the id value to determine where the number of seconds remaining should be published.
The JavaScript needs to be in the web page source code somewhere after the above countdown number code where the countdown number is published.
Here is the JavaScript. The three customizations are addressed after the source code.
<script type="text/javascript"> // Verify next three values. var NumSeconds_NumberContainer = "number-of-seconds-to-go"; var NumSeconds_Destination = "https://example.com/"; var NumSeconds_CurrentNumberOfSeconds = 12; // Verify above three values. var NumSeconds_Timer = false; function UpdateNumberOfSeconds() { document.getElementById(NumSeconds_NumberContainer).innerHTML=NumSeconds_CurrentNumberOfSeconds; NumSeconds_CurrentNumberOfSeconds--; if(NumSeconds_CurrentNumberOfSeconds<0) { window.location=NumSeconds_Destination; clearInterval(NumSeconds_Timer); } } NumSeconds_Timer = setInterval(UpdateNumberOfSeconds,1000); UpdateNumberOfSeconds(); </script>
Comments
The number-of-seconds-to-go
value is identical to the id value of the code where the countdown number is to be published. If one changes, the other needs to be changed accordingly.
The https://example.com/
value is the URL where the browser shall be redirected to when the countdown completes.
The 12
is the number of seconds for the timer to measure.
As noted earlier, the JavaScript needs to be in the web page source code somewhere after the code where the countdown number is published.
That is all there's to it: The spot where the countdown number is published and the JavaScript to do the countdown.
A timer like this can be useful when the site visitor should be aware about something related to the current web page before the redirect kicks in.
(This content first appeared in Possibilities newsletter.)
Will Bontrager