Explain Codes LogoExplain Codes Logo

Onclick javascript to make browser go back to previous page?

javascript
onclick-event
browser-history
javascript-functions
Nikita BarsukovbyNikita Barsukov·Aug 28, 2024
TLDR

Snapshot of the answer: to navigate to the browser's previous page, add window.history.back() to onclick event handler:

<button onclick="window.history.back()">Go Back</button>

The above HTML button triggers back function when clicked, emulating the user's back button action.

Extended controls and functionality

Canceling form submission

To prevent the form from being submitted during navigation, use return false; in the onclick event:

<button onclick="window.history.back(); return false;">Cancel</button>

To go back more than a single page, use history.go(-x) where x is the number of pages:

<button onclick="history.go(-2)">Go Back Two Pages</button>
<!-- Can't blame a user wanting to time-travel 😅 -->

Swapping button with anchor tag

Anchor tag might provide a better user experience in some scenarios:

<a href="javascript:void(0);" onclick="window.history.back();">Go Back</a>

This prevents the default link action, with actual navigation managed by onclick event.

Get to know your back()

window.history.back() and history.back() are interchangeable. But keeping window can improve readability and handle multiple window contexts.

Clear cue to action

Visual distinction for Cancelling

For maximum user experience, style Cancel button differently:

.cancel-button { background-color: #f44336; /* Red color screams, "Stop!!" */ color: white; } <!-- If button was a cop, it'd say "Halt"! 🚨 --> ### Bringing it to practice Here’s how you'd put it in your code: ```html <button onclick="window.history.back(); return false;" class="cancel-button">Cancel</button>

Form loyalties

Reveal button's intent by setting its type to button to indicate it won't submit a form:

<button type="button" onclick="window.history.back();">Go Back</button>
<!-- No fake promises here 👮🏽‍♀️ -->

Handling Inline JavaScript

Resolving conflicts

Assign the onclick event via JavaScript, separating JavaScript from HTML to debug more easily:

document.getElementById('goBackButton').addEventListener('click', function() { history.back(); });

The redundancy

Including window. can be optional, however it enhances clarity for code newbies:

<button onclick="window.history.back(); return false;">Go Back</button>

Additional Considerations

Cross-browser compatibility

history.back() and history.go(-1) are supported in most modern browsers but consider those ancient browser versions too.

Handling buttons in dynamic environments

In a single-page application (SPA) or dynamically loaded content, ensure your program respects the history state.

Using history statefully

Optimize UX by using history.pushState() and history.replaceState() for more intuitive history records.

Listen for history changes

To reactively manage UI state changes, use the window.onpopstate event.