Javascript
JS intro
JS basics
JS variables
JS functions
JS popup boxes
JS conditional logic
JS loops
JS arrays
JS objects
JS strings
JS events
JS errors
JS DOM
JS elements
JS new windows
JS date and time
JS cookies
JS print
JS redirect
JS void 0
JS Summary

Programming

Programming intro
Java

Markup

First webpage guide
HTML
XHTML

Style & Layout

CSS

Browser scripting

VBScript
AJAX

Server scripting

PHP
ASP

Making money online

Make money online

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 lesson focuses on:

The window.location property

Javascript provides the functionality for redirects through the usage of the window.location property. This property will redirect a page to a location 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 main 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

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments