Using Javascript to redirect to another web page



Javascript can be used to do a number of cool things, and it can either work automatically or in response to something the user does, called an "event". In this lesson, we use Javascript to automatically redirect the browser to another web page.

This could be useful if you were to change the name of an HTML document on the web, for example. You want users to go to the new page, but your existing page has already been archived by search engines, people may have already bookmarked the old page, etc., so you would like to create a way for people to find the new page while using the old link. A single line of Javascript can allow you to redirect the user to the new page:
        <script type="text/javascript">
          <!--
            window.location="http://www.gecko-ak.org/javascript"
          //-->
        </script>
      
OK, technically, there are five lines in the above snippet of code, but only one of those lines is Javascript -- the rest is either HTML or a Javascript comment. Anyway, the "window.location" method is used to tell the web browser to load a new page of content in place of the existing document.

In another lesson we will discuss how to pause a script for a few seconds, which could be useful if you want to alert the user that you are redirecting them to another page. Alternatively, there are a number of ways that you could wait for user input before redirecting to the new page. We will discuss some of these in later lessons, too.

For now, however, we will keep it simple by just introducing the "window.location" method.

Here is how it looks on the web.