How to Go Back to Previous Page in Javascript
In this tutorial, you will learn how to go back to previous page using javascript. Almost in every browser, we have a back button to navigate back to the previous page.
The functionality of the back button is based on browser history which makes it easy for a user to go and back forth. But sometimes we do want to implement such functionality programmatically and allow a user to go back to the previous page on button click.
To accomplish our goal, we can make use of the History
object. This object has various helpful methods and properties to manipulate history of browser session. One of those methods is the back()
method which takes a user back to the previously navigated page dynamically. To learn more about History
object, please check out MDN docs.
In the following example, we have multiple HTML pages. We will navigate back and forth between those pages using anchor elements and javascript. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 HTML pages (
index
,page1
, andpage2
). - The
index
page contains 2 anchor elements so that we can navigate topage1
andpage 2
. - Both pages
page1
andpage2
contain button elements with aninnerText
of“Go Back”
. Upon click of this button, we will take the user back to theindex
page using javascript. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom of both pagespage1
andpage 2
.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div> <h1>Home Page</h1> <a href="/page1.html">Page 1</a> <a href="/page2.html">Page 2</a> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div> <h1>Page 1</h1> <button>Go Back</button> </div> <script src="script.js"></script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div> <h1>Page 2</h1> <button>Go Back</button> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; }
Javascript
- We have selected the
button
element using thedocument.querySelector()
method and stored it in thebtnBack
variable. - We have attached a
click
event listener to thebutton
element. - In the event handler function, we are calling the
back()
method to navigate back to the previous page.
let btnBack = document.querySelector('button'); btnBack.addEventListener('click', () => { window.history.back(); });