Implement Onclick in JavaScript and allow web browser to go back to previous page?

JavaScript provides several methods to implement browser navigation functionality. The most common approach is using window.history.go(-1) with an onclick event to go back to the previous page.

Syntax

window.history.go(-1);    // Go back one page
window.history.back();    // Alternative method

Using window.history.go(-1)

The window.history.go(-1) method navigates back one page in the browser history:

<!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>
</head>
<body>
    <h1>Current Page</h1>
    <button onclick="window.history.go(-1)">
        Go Back to Previous Page
    </button>
</body>
</html>

Using window.history.back()

The window.history.back() method is an alternative that provides the same functionality:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Go Back Alternative</title>
</head>
<body>
    <h1>Current Page</h1>
    <button onclick="window.history.back()">
        Back
    </button>
</body>
</html>

Using a Separate Function

For better code organization, you can create a separate function:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Go Back with Function</title>
</head>
<body>
    <h1>Current Page</h1>
    <button onclick="goBack()">
        Go Back
    </button>

    <script>
        function goBack() {
            window.history.go(-1);
        }
    </script>
</body>
</html>

Comparison

Method Description Usage
window.history.go(-1) Navigate back one page More explicit
window.history.back() Navigate back one page Shorter syntax

Key Points

  • Both methods work identically for going back one page
  • The browser must have a previous page in history for these methods to work
  • These methods only work in browser environments, not in Node.js
  • Use return false; if you want to prevent form submission

Conclusion

Use window.history.go(-1) or window.history.back() to implement back navigation. Both methods are reliable for creating back buttons in web applications.

Updated on: 2026-03-15T23:18:59+05:30

499 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements