Redirecting to Another Page Using JavaScript

In web development, redirecting users to another page is a common task, and JavaScript provides a simple way to achieve this programmatically.

Whether you need to navigate users to a different section of your website or an external URL, JavaScript's "window.location" object comes in handy.

In this article, we'll explore how to use JavaScript to redirect to another page.

Using "window.location"

The window.location object in JavaScript provides information about the current URL and allows you to navigate to a new one.

By assigning a new URL to window.location.href, you can redirect users to another page.

Let's create a simple function to handle the redirection:

// Function to redirect to another page
function redirectToPage(url) {
  // Set the new URL
  window.location.href = url;
}

In this code:

Example: Redirecting on Button Click

Let's create a complete example where clicking a button triggers a redirection to another page:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Redirect Example</title>
  <style>
    /* Optional styling for better presentation */
    body {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100vh;
      margin: 0;
    }

    button {
      padding: 10px;
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <button onclick="redirectToPage('https://example.com')">Go to Example.com</button>

  <script>
    // Function to redirect to another page
    function redirectToPage(url) {
      // Set the new URL
      window.location.href = url;
    }
  </script>
</body>
</html>

In this example:

Conclusion

Redirecting to another page using JavaScript is a straightforward process that involves assigning a new URL to window.location.href.

Whether you're navigating users within your website or sending them to an external link, this technique allows for seamless page redirection.

Incorporate this functionality into your projects to enhance user navigation and provide a more dynamic and interactive web experience.