Home | SkillForge Blog | Redirect a Webpage using JavaScript

Redirect a Webpage using JavaScript

JavaScript, Web Design

Sometimes you might move a webpage to some other location but you still have people going to the old one.  We are able to redirect the users to the new page using JavaScript.  To do this, we would start with your basic HTML page, we’ll pretend this is the old page people are still going to:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>Old Page</title>
</head>
<body>
Old Page
</body>
</html>

Now we want to add a piece of JavaScript that will redirect the user to the new page.  To do that we need to add script tags either in the head tag or right above the closing body tag:

<head>
<meta charset=”utf-8″>
<title>Old Page</title>
<script></script>
</head>

Once we’ve done that we will use the location object built into JavaScript to do the redirect.  Inside the script tags we will add the following:

<script>
location = “http://www.google.com”;
</script>

location is a short way of using the location property found in the location JavaScript object.  It will set the URL to the page to whatever you put inside the quotes.  In this example, I’m redirecting to Google but you could put whatever you want in there.  It could be anything like:

location = “http://www.yourdomain.com”;

which would redirect you to your website.  Or

location = “someFile.html”;

which would redirect you to a file found on your web server.  Either way, you have a lot of control over where the user goes when they get to the page.  Here is the completed code:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>Old Page</title>
<script>
location = “http://www.google.com”;
</script>
</head>
<body>
Old Page
</body>
</html>

If you’d like to learn more be sure to check out our HTML/CSS/JavaScript training.  Have an amazing day!