Skip to content

Redirect to another page JavaScript

  • by

JavaScript provides two popular methods to redirect to another webpage: location.href and location.replace. The location.href method sets the href property of the location object to the URL of the new page, causing the browser to navigate to that page.

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

The location.replace method replaces the current page with the new page, without adding a new entry to the browser’s history.

window.location.replace("https://www.example.com");

Both methods can be used to redirect to another page, but they have different effects on the browser’s history.

Redirect to another page JavaScript example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Redirect to Another Page</title>
</head>
<body>
  <button onclick="redirectToPage()">Go to EyeHunts.com</button>

  <script>
    function redirectToPage() {
      location.href = "https://EyeHunts.com";
    }
  </script>
</body>
</html>

Output:

Redirect to another page JavaScript

here’s another example of how to redirect to another webpage using JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>Redirect to Another Page</title>
</head>
<body>
  <p>Click the button below to go to Example.com:</p>
  <button id="redirectButton">Go to EyeHunts.com</button>

  <script>
    // Add an event listener to the button element
    document.getElementById("redirectButton").addEventListener("click", function() {
      // Redirect to the new page
      location.replace("https://EyeHunts.com");
    });
  </script>
</body>
</html>

Note: the browser may block automatic redirects in some cases, such as when they are initiated by a popup window or are triggered by user interaction. You can use a link with the target="_blank" attribute to open the new page in a new tab or window.

Do comment if you have any doubts or suggestions on this HTML webpage topic.

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

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

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

Continue reading