Skip to content

JavaScript redirect on page load

  • by

To redirect a page using JavaScript on page load, you can use the window.location object to set the URL of the page. Here’s the syntax:

window.onload = function() {
  // Redirect to the desired URL
  window.location.href = 'https://example.com/new-page';
};

Alternatively, you can use the window.location.replace() method to achieve the redirect:

window.onload = function() {
  // Redirect to the desired URL
  window.location.replace('https://example.com/new-page');
};

If you want to redirect the page using a meta tag in the page’s HTML, you can use the <meta> tag with the http-equiv attribute set to “refresh”.

<head>
  <title>Redirect Page</title>
  <meta http-equiv="refresh" content="0;url=https://example.com/new-page">
</head>

JavaScript redirect on page load example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Redirect Page</title>
  <script>
    window.onload = function() {
      // Redirect to the desired URL after a delay of 3 seconds
      setTimeout(function() {
        window.location.href = 'https://eyehunts.com';
      }, 3000); // Delay in milliseconds (3 seconds)
    };
  </script>
</head>
<body>
  <!-- Content of your page -->
</body>
</html>

Output:

JavaScript redirect on page load

In the above example, the page will redirect to the URL after a delay of 3 seconds. The window.onload event handler waits for the page to finish loading, and then the setTimeout() function is used to delay the execution of the redirection code.

You can adjust the delay by changing the value in setTimeout() to the desired number of milliseconds.

How to Redirect to Another Webpage Using JavaScript

Answer: To redirect to another webpage using JavaScript, you can utilize the window.location object. Here are a few examples of how to redirect:

Basic Redirect:

window.location.href = "http://www.example.com";

After Delay:

setTimeout(function() {
  window.location.href = "http://www.example.com";
}, 3000); // Redirect after 3 seconds

Redirect in Response to an Event (e.g., button click):

<button onclick="redirect()">Click Me</button>

<script>
  function redirect() {
    window.location.href = "http://www.example.com";
  }
</script>

Open Redirect in New Tab/Window:

window.open("http://www.example.com", "_blank");

Comment if you have any doubts or suggestions on this JS HTML topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading