Yogesh Chauhan's Blog

3 JavaScript methods to use when you want to go back and forth in history

in JavaScript on April 25, 2019

The DOM Window object provides access to the browser’s session history through the history object.

Moving backward and forward through the user’s history is done using the back(), forward(), and go() methods.

Moving forward and backward

window.history.back() method in JavaScript

To move backward through history use this:



window.history.back()


The back() method loads the previous URL in the history list. This acts exactly as if the user clicked on the Back button in their browser toolbar.

How to use it?

Just add the following cod in your button.



onclick="window.history.back()"


window.history.forward() method in JavaScript

Similarly, you can move forward (as if the user clicked the Forward button), using this:



window.history.forward()


The forward() method loads the next URL in the history list.

How to use it?

Just add the following cod in your button.



onclick="window.history.forward()"


Moving to a specific point in history

go() method

The go() method loads a specific URL from the history list.

You can use the go() method to load a specific page from session history, identified by its relative position to the current page, current page’s relative position = 0.

How to use it?



window.history.go(-1)

//same as using back() method

window.history.go(1)

//same as using forward() method

For 2 it will go forward 2 pages and for -2 it will go back 2 pages.

What if you add 0?

It will refresh the current page!

We can refresh the current page by either passing 0, or by invoking it without an argument.

For example,



window.history.go(0)
window.history.go()

//both will refresh the current page



Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
5 Key Principles Of Good Website UsabilityUI/UXSlider animation using CSS transform propertyCSSHow to add a ribbon inside a container using CSS?CSSclip and clip-path properties in CSSCSSHow to overwrite file contents with new content in PHP?PHPUse SwiperJS to create mobile touch sliders fastMiscellaneous