There is an easy technique you can use in JavaScript to redirect your users. This may be helpful in a scenario where you are moving your website
from an old domain to a new domain. There are many other methods you can implement to achieve the same goal, but we will go over how to do this
using JavaScript code.
When your web page is moved, it would be a good idea to notify your visitors of the change. You can create add JavaScript code to your old home page,
add a timer, and forward visitors to the new location of your website.
JavaScript window.location
We can control which page loads in the current window using the window.location
property. By setting the window.location to a new URL, the visitor's web browser
will load the new specified URL. Here is an example of how to redirect users. In
the first example, we just assign the string value of the URL to the
window.location property. In the second example, we use the location object's
assign method. Both produce the same results.
<script type="text/javascript">
<!--
window.location = "http://www.itgeared.com/"
//-->
</script>
Include a Time Delay
It may confuse your visitors if they are immediately redirected to another page when visiting the old URL. Additionally, the time delay could
be useful if you want to show a timer before a user is allowed to click on a link, or if you want to refresh the page on a routine cycle. Here is an
example of how you would include a timer before redirecting a user to another page.
<html>
<head>
<script type="text/javascript">
<!--
function delay() {
window.location.assign("http://www.itgeared.com")
}
//-->
</script>
</head>
<body onLoad="setTimeout('delay()', 3000)">
<h2>Prepare to be redirected!</h2>
<p>See you at the new site!</p>
</body>
</html>
Location Object
The location object contains information about the current URL. The location
object is part of the window object and is accessed through the window.location
property. The following properties and methods can be used for the location object.
Properties
Property | Description |
hash | Returns the anchor portion of a URL |
host | Returns the hostname and port of a URL |
hostname | Returns the hostname of a URL |
href | Returns the entire URL |
pathname | Returns the path name of a URL |
port | Returns the port number the server uses for a URL |
protocol | Returns the protocol of a URL |
search | Returns the query portion of a URL |
Methods
Method | Description |
assign() | Loads a new document |
reload() | Reloads the current document |
replace() | Replaces the current document with a new one |
You should note that there is no public standard that applies to the location object, but all major browsers support it.
Did you find the page informational and useful? Share it using one of your favorite social sites.
Recommended Books & Training Resources