Javascript redirect
You have a situation where you need to redirect one URL to another. Some would say, for what purpose? There can be a few reasons for this. One is you've changed your domain name and whenever someone accesses the old domain name, you want to redirect them to the new domain name. Another reason could be that a page on your website no longer exists, but you want to redirect people trying to access that page to a new page.
This tutorial focuses on:
- The window.location property
- Time delay redirects
The window.location property
Javascript provides the functionality for redirects through the usage of the window.location property. This property will redirect the user to a page you specify.
The above example will redirect to landofcode.com home page
Time delay redirects
What if you want to give the user a message first and redirect them to another page only after a certain amount of time instead of doing it right away? You can do this using time delay redirects.
The above example uses a method you may have not seen before, that method is the setTimeout() method. It is this method that drives the time delay redirect. The method is included in the onload event handler in the <body> tag signifying that the method should execute when the page first loads. The setTimeout() method takes two arguments. The first argument specifies the function to perform a time delay on, in this case it is redirecUser(). The second argument specifies in how many milliseconds the function should be executed. Every 1000 milliseconds = 1 second, so in this case it is five seconds. The function will therefore execute five seconds after the page fully loads and redirect the user to the page javascript-redirect.php
Click here to view the time delay script page which uses the above code