DEV Community

Cover image for How to go 2 pages back or front in history using JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to go 2 pages back or front in history using JavaScript?

Originally posted here!

To go back or front to a specific page in history, you can use the go() function in the global history object and pass the count as an argument to the function in JavaScript.

In our case, we want to go 2 pages back in the history. So for that, we can pass -2 as an argument to the history.go() function like this,

// Go 2 pages back in history
history.go(-2);
Enter fullscreen mode Exit fullscreen mode

If we want to go 2 pages front in history, we need to omit the negative sign from the -2, so it may look like this

// Go 2 pages front in history
history.go(2);
Enter fullscreen mode Exit fullscreen mode
  • Negative number values are used to go back to a specific page.
  • Positive number values are used to go forward to a specific page.

See this example live in JSBin.

Feel free to share if you found this useful 😃.


Top comments (0)