Onclick javascript to make browser go back to previous page?
Snapshot of the answer: to navigate to the browser's previous page, add window.history.back()
to onclick
event handler:
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:
Navigating multiple pages back
To go back more than a single page, use history.go(-x)
where x
is the number of pages:
<!-- 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:
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:
Form loyalties
Reveal button's intent by setting its type to button
to indicate it won't submit a form:
<!-- No fake promises here 👮🏽♀️ -->
Handling Inline JavaScript
Resolving conflicts
Assign the onclick
event via JavaScript, separating JavaScript from HTML to debug more easily:
The redundancy
Including window.
can be optional, however it enhances clarity for code newbies:
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.
Was this article helpful?