YogeshChauhan . com

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


amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to add onclick event to html elements dynamically using JavaScript?JavaScriptHow to Make CSS Lists Bullets Smaller?CSSOverview of Drupal and how it worksDrupalHow to check if checkbox is checked or not using JavaScript?JavaScriptArray destructuring and Object destructuring in JavaScriptJavaScriptCREATE DATABASE in PostgreSQLPostgres