I am online
← Back to Articles

Navigate To The Previous and Next Page In JavaScript

JavaScriptMay 16, 2024

Introduction

Redirecting users from one page to another is a very common operation in web applications.

Imagine you are implementing a profile page that is accessible from both, page A and page B.

History API

The History API provides access to browsing history via window.history by providing useful methods and properties that allow you to navigate back and forth through the user's history and manipulate the contents of the history stack.

For the purpose of our today's task it provides three methods:

  • window.history.back() : This method behaves exactly like the browser's back button.

  • window.history.forward() : This method behaves exactly like the browser's forward button.

  • window.history.go([d]) : This method loads a specific page from the browser's history.

Navigate Back

const navigateBack1 = () => {
  window.history.back();
};

const navigateBack2 = () => {
  window.history.go(-1);
};

Navigate Forward

To navigate forward in history, we use window.history.forward() or window.history.go(1):

const navigateForward1 = () => {
  window.history.forward();
};

const navigateForward2 = () => {
  window.history.go(1);
};

Thanks for reading, enjoy, and happy coding!