Javascript
  1. Javascript intro
  2. Javascript basics
  3. Javascript variables
  4. Javascript functions
  5. Javascript popup boxes
  6. Javascript conditions
  7. Javascript loops
  8. Javascript arrays
  9. Javascript objects
  10. Javascript strings
  11. Javascript events
  12. Javascript errors
  13. Javascript DOM
  14. Javascript elements
  15. Javascript new windows
  16. Javascript date & time
  17. Javascript cookies
  18. Javascript print
  19. Javascript redirect
  20. Javascript void
  21. Javascript summary

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

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.

Syntax
window.location = "pageToRedirectTo";
Example:
<script type="text/javascript"> window.location = "http://www.landofcode.com"; </script>

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.

Example:
<html> <head> <script type="text/javascript"> function redirectUser(){ window.location = "javascript-redirect.php"; } </script> </head> <body onload="setTimeout('redirectUser()', 5000)"> <h1>You will be redirected to the Javascript redirect page in five seconds!</h1> </body> </html>

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

© Copyright 2013-2014 Landofcode.com
Terms of use | Privacy policy | Copyright information