Navigating Back to the Previous Page Using JavaScript

JavaScript provides a simple and effective way to achieve this using the window.history object.

In this article, we'll explore how to use JavaScript to go back to the previous page in the browser's history.

Using "window.history"

The window.history object in JavaScript represents the browser's session history.

By utilizing the go method with a negative value, you can instruct the browser to navigate backward in the history.

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

// Function to go back to the previous page
function goBack() {
  // Navigate back in the history
  window.history.go(-1);
}

In this code:

Example: Going Back on Button Click

Let's create a complete example where clicking a button triggers a navigation back to the previous page:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Go Back 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="goBack()">Go Back</button>

  <script>
    // Function to go back to the previous page
    function goBack() {
      // Navigate back in the history
      window.history.go(-1);
    }
  </script>
</body>
</html>

In this example:

Conclusion

Navigating back to the previous page using JavaScript is a simple and effective way to enhance user navigation within your web application.

By leveraging the window.history object, you can provide users with a seamless experience as they move through the pages they've visited.

Incorporate this functionality into your projects to improve the overall usability of your web applications.