JavaScript

Redirect the Page-on-Page Load Using window.location

Redirect a web page to another page using JavaScript Redirect Method. In JavaScript, window.location method used to get information about the location of the current web page.

In order to redirect another website immediately after your website is opened, you can use the following code:

<script>
  window.location.href = "http://www.smartlearningtutorials.com";
</script>

Redirect the page after a certain period of time.

In order to redirect another website after a certain time period, you can use the following code:

<script>
  setTimeout(function() {
    window.location.href = "http://www.smartlearningtutorials.com";
  }, 3000);
</script>

You can change 3000 (3 x 1000 in milliseconds) as requirement.

Redirect the Page after an Event or User Action

Sometimes, you may want to send the user to another page after a certain event or action takes place, such as a button click, an option selection, a countdown timer expiration or etc. You can redirect a web page using a condition check or assign an event to an element.

Below are the examples of redirect a page based on Event or User Action:

Redirection a page if the condition is true.

<script>
  // Check if the condition is true and then redirect.
  if ( ... ) {
    window.location.href = "http://www.smartlearningtutorials.com";
  }
</script>

Redirection a page when the user clicks the #button element.

<script>
  // onclick event is assigned to the #button element.
  document.getElementById("button").onclick = function() {
  window.location.href = "http://www.smartlearningtutorials.com";
};
</script>

In this tutorial, we will learn how to create redirect a page using JavaScript by given examples.

The following is a list of possible ways that can be used as a JavaScript redirect:

// Sets the new location of the current window.
window.location = "http://www.smartlearningtutorials.com";

// Sets the new href (URL) for the current window.
window.location.href = "http://www.smartlearningtutorials.com";

// Assigns a new URL to the current window.
window.location.assign("http://www.smartlearningtutorials.com");

// Replaces the location of the current window with the new one.
window.location.replace("http://www.smartlearningtutorials.com");

// Sets the location of the current window itself.
self.location = "http://www.smartlearningtutorials.com";

// Sets the location of the topmost window of the current window.
top.location = "http://www.smartlearningtutorials.com";

Redirect Page Using JavaScript

You can customize this code further as per your requirement.