How to generate a “go to previous page” button with JavaScript?

Sometimes you want to add a button to a website that tells the browser to return to the previous page.

Yes, I know, the browser itself has such a function but there are sometimes cases where it makes sense to include a “back to previous page” button directly into the page.

Here is an example of an HTML page that includes a “Go Back” button that utilizes JavaScript to go to the previous page when clicked:

<!DOCTYPE html>
<html>
  <head>
    <title>Go Back Button Example</title>
    <style>
        /* Add your CSS rules here */
        body {
          background-color: #f2f2f2;
          font-family: Arial, sans-serif;
        }
    
        h1 {
          color: #0a3200;
          font-size: 32px;
        }
    
        button {
          background-color: #83ad25;
          color: #fff;
          border: none;
          padding: 10px 20px;
          font-size: 16px;
          cursor: pointer;
        }
      </style>
  </head>
  <body>
    <h1>Welcome to my website</h1>
    <button onclick="goBack()">Go Back</button>  <!-- The HTML part -->

    <script>  // The JavaScript part
      function goBack() {
        window.history.back();
      }
    </script>
  </body>
</html>
  • Within the “script” code, a function called “goBack()” is defined that utilizes the “window.history” object to go back one page in the browsing history when called.
  • The “onclick” attribute on the button element is assigned the value of “goBack()”, so when the button is clicked, the function is executed, and the browser navigates back to the previous page in the history.

Quick notes

  • Note that using the “window.history” object in JavaScript can have some limitations, based on the user’s browser and their browsing history.
  • Also, this code assumes that the previous page in the browsing history is the page that the user wants to go back to, which may not always be the case.

Leave a Reply

Your email address will not be published. Required fields are marked *