How to Trigger Browser's Back Event Using JavaScript: Implementing Back Functionality via Hyperlinks

In web development, enhancing user navigation is critical for a seamless experience. One common requirement is allowing users to "go back" to the previous page, mimicking the browser’s native back button. While browsers provide a built-in back button, there are scenarios where you might want to add this functionality directly into your UI—for example, in a custom navigation bar, a modal, or a multi-step form.

This blog will guide you through triggering the browser’s back event using JavaScript, with a specific focus on implementing this via hyperlinks (<a> tags). We’ll cover the underlying Browser History API, multiple methods to bind back functionality to hyperlinks, edge cases, best practices, and accessibility considerations. By the end, you’ll be able to add robust "go back" links to your web projects with confidence.

Table of Contents#

  1. Understanding the Browser History API
    • What is the History API?
    • Key Methods: history.back() and history.go()
  2. Triggering Back Event via Hyperlinks: Methods
    • Method 1: Inline onclick Event Handler
    • Method 2: Using href with javascript: Protocol
    • Method 3: Unobtrusive JavaScript (Event Listeners)
  3. Handling Edge Cases
    • No Previous History to Navigate Back To
    • Preventing Unintended Page Scrolling
  4. Advanced Use Cases
    • Going Back Multiple Pages with history.go(-n)
    • Single-Page Applications (SPAs) and the History API
  5. Accessibility Considerations
  6. Common Pitfalls and Best Practices
  7. Conclusion
  8. References

Understanding the Browser History API#

Before diving into implementation, it’s essential to understand the tool that makes back navigation possible: the Browser History API.

What is the History API?#

The History API is a built-in JavaScript interface (window.history) that allows you to interact with the browser’s session history (the list of pages visited in the current tab). It enables you to manipulate the history stack, navigate forward/backward, and even modify the URL without reloading the page (critical for SPAs).

Key Methods: history.back() and history.go()#

For triggering the "back" event, two methods are most relevant:

1. history.back()#

This method simulates clicking the browser’s native back button. It navigates the user to the previous page in the session history, equivalent to history.go(-1).

Example:

// Go back to the previous page
history.back();

2. history.go(n)#

This method navigates the user n steps forward or backward in the history stack.

  • Use history.go(-1) to go back 1 page (same as history.back()).
  • Use history.go(-2) to go back 2 pages.
  • Use history.go(1) to go forward 1 page (equivalent to history.forward()).

Example:

// Go back 2 pages
history.go(-2);

Hyperlinks (<a> tags) are the most intuitive way to add clickable elements for navigation. Below are three methods to bind the "back" functionality to hyperlinks using JavaScript.

Method 1: Inline onclick Event Handler#

The simplest way to trigger the back event is to use the onclick attribute directly in the hyperlink. This inline approach executes JavaScript when the link is clicked.

How It Works:#

Add onclick="history.back()" to the <a> tag. To prevent the browser from following the link’s default href (which might cause unintended behavior, like scrolling to the top with href="#"), use event.preventDefault() or return false.

Example 1: Basic onclick with preventDefault()#

<!-- "Go Back" link using inline onclick -->
<a href="#" onclick="event.preventDefault(); history.back();">
  ← Go Back to Previous Page
</a>
  • href="#": A placeholder to ensure the link behaves like a clickable element (cursor changes to pointer, keyboard focus works).
  • event.preventDefault(): Stops the browser from navigating to # (which would scroll the page to the top).
  • history.back(): Triggers the back event.

Example 2: onclick with return false#

Alternatively, you can use return false to both prevent default behavior and stop event propagation:

<a href="#" onclick="history.back(); return false;">
  ← Go Back
</a>

Note: return false is equivalent to calling event.preventDefault() and event.stopPropagation(). Use this if you want to block parent event listeners from firing.

Method 2: Using href with javascript: Protocol#

Another approach is to embed the JavaScript directly in the href attribute using the javascript: protocol. This tells the browser to execute the code instead of navigating to a URL.

Example:#

<!-- "Go Back" link using javascript: protocol -->
<a href="javascript:history.back()">
  ← Go Back
</a>

Pros:

  • No need for preventDefault() (the javascript: protocol handles this automatically).
  • Concise syntax for simple use cases.

Cons:

  • Less maintainable for complex logic (mixes HTML and JavaScript).
  • Some linters or security tools may flag javascript: URLs as risky (though they’re safe for simple back navigation).

Method 3: Unobtrusive JavaScript (Event Listeners)#

For cleaner code separation (HTML for structure, JavaScript for behavior), use unobtrusive JavaScript. This involves adding a click event listener to the hyperlink via an external or inline script, rather than using inline onclick.

First, define the hyperlink in HTML with a unique identifier (e.g., id="backLink"):

<!-- "Go Back" link (unobtrusive JS) -->
<a href="#" id="backLink">
  ← Go Back to Previous Page
</a>

Step 2: Attach an Event Listener in JavaScript#

Then, in your JavaScript file or <script> tag, select the link and bind a click event listener:

// Get the link element by ID
const backLink = document.getElementById('backLink');
 
// Add click event listener
backLink.addEventListener('click', (event) => {
  event.preventDefault(); // Prevent default href="#" behavior
  history.back(); // Trigger back event
});

Why This is Better:#

  • Separation of concerns: HTML and JavaScript are decoupled, making code easier to maintain.
  • Reusability: You can reuse the same logic for multiple links by targeting a class instead of an ID.
  • Flexibility: Add conditional logic (e.g., check if history exists) before triggering history.back().

Handling Edge Cases#

Even with the methods above, you’ll encounter scenarios that require extra handling. Let’s address the most common edge cases.

No Previous History to Navigate Back To#

If the user lands directly on your page (e.g., via a bookmark or direct URL), there may be no previous history to go back to. In this case, history.back() will do nothing (or, in some browsers, navigate to a blank page).

Solution: Check history.length#

The history.length property returns the number of entries in the session history stack. A value of 1 means there’s only the current page (no previous history).

Example: Conditional Back Navigation

// Unobtrusive JS with history check
const backLink = document.getElementById('backLink');
 
backLink.addEventListener('click', (event) => {
  event.preventDefault();
 
  // Check if there's previous history
  if (history.length > 1) {
    history.back(); // Go back if history exists
  } else {
    // Fallback: Redirect to home page or show a message
    window.location.href = '/home'; // Or alert("No previous page!");
  }
});

Preventing Unintended Page Scrolling#

Using href="#" without event.preventDefault() (or return false) causes the browser to scroll to the top of the page (since # is the "top of page" anchor). Always include preventDefault() to avoid this.

Bad Practice (Causes Scrolling):#

<!-- ❌ Avoid: href="#" without preventDefault() -->
<a href="#" onclick="history.back()">Go Back</a> <!-- Triggers scroll to top! -->

Good Practice (Prevents Scrolling):#

<!-- ✅ Good: Use preventDefault() or javascript: protocol -->
<a href="#" onclick="event.preventDefault(); history.back();">Go Back</a>

Advanced Use Cases#

Going Back Multiple Pages with history.go(-n)#

To navigate back more than one page (e.g., 2 pages), use history.go(-n), where n is the number of steps.

Example: Go Back 2 Pages#

<!-- Go back 2 pages -->
<a href="javascript:history.go(-2)">
  ← Go Back 2 Pages
</a>

Note: Use history.length to ensure there are enough pages to go back:

// Go back 2 pages only if history exists
if (history.length > 2) {
  history.go(-2);
} else {
  alert("Not enough history to go back 2 pages!");
}

Single-Page Applications (SPAs) and the History API#

In SPAs (e.g., React, Vue, Angular), navigation often happens without full page reloads. The History API’s pushState() method is used to update the URL and history stack dynamically.

For SPAs, history.back() will still work, but it will trigger a popstate event instead of reloading the page. Your SPA framework will handle this event to render the previous view.

Example: SPAs with pushState and history.back()#

// In an SPA: Add a new entry to history (simulate navigation)
history.pushState({ page: "page2" }, "Page 2", "/page2");
 
// Later, trigger back to return to the previous state
history.back(); // Triggers popstate event; SPA renders "page1"

Accessibility Considerations#

Ensure your "go back" links are usable by all users, including those with disabilities. Here are key accessibility tips:

1. Keyboard Accessibility#

Hyperlinks are natively keyboard-accessible (users can tab to them and press Enter to click). Avoid using non-link elements (e.g., <div>) for back functionality, as they require extra work to make keyboard-accessible.

2. Screen Reader Friendliness#

If the link text is generic (e.g., "← Go Back"), add an aria-label to clarify its purpose for screen readers:

<a href="#" onclick="event.preventDefault(); history.back();" aria-label="Go back to the previous page">
  ← Go Back
</a>

3. Visible Focus Styles#

Ensure the link has a visible focus indicator (e.g., a border or shadow) when tabbed to. Browsers provide default styles, but you can customize them with CSS:

/* Custom focus style for back link */
#backLink:focus {
  outline: 2px solid #2196F3; /* Blue outline */
  outline-offset: 2px;
}

Common Pitfalls and Best Practices#

Pitfall 1: Forgetting preventDefault() with href="#"#

Always use event.preventDefault() (or return false) when using href="#" to avoid page scrolling.

Pitfall 2: Not Handling Empty History#

If history.length === 1, history.back() will do nothing (or navigate to a blank page in older browsers). Always check history.length if fallback behavior is needed.

Pitfall 3: Overusing javascript: URLs#

While javascript:history.back() works, prefer unobtrusive event listeners for maintainability in larger projects.

Instead of generic text like "Click here", use descriptive text like "← Go Back to Product List" to improve usability and SEO.

Best Practice: Test Across Browsers#

Most modern browsers (Chrome, Firefox, Safari, Edge) support the History API consistently, but test edge cases (e.g., private browsing, iframes) if your app relies heavily on back navigation.

Conclusion#

Triggering the browser’s back event via hyperlinks is a common web development task, and the Browser History API makes it straightforward. Whether you use inline onclick, javascript: URLs, or unobtrusive event listeners, the core method remains history.back().

  • For simple cases: Use href="javascript:history.back()" or inline onclick.
  • For maintainability: Use unobtrusive event listeners to separate HTML and JavaScript.
  • For robustness: Handle edge cases like empty history and ensure accessibility.

By following the methods and best practices in this guide, you’ll create intuitive, reliable "go back" links that enhance user navigation.

References#