JavaScript

Javascript History Back Example

Everyone who has ever used a computer knows what the Back Button is. We’ve seen it in browsers, apps, everywhere. It is claimed to be the second most used navigation feature again, and according to Mozilla, it is their most clicked Firefox button.

If users (and you too) find this feature this useful, why in the world would you not include it in your latest project? If you’re using Javascript, here’s how to do it.
 
 
 
 
 

History Back

First of all, history back! You can build a button which goes back one page like below. To start with, you create two files, an HTML one named index.html and a Javascript one named historyback.js in my case, but you can name them whatever you want.

You put this code snippet in historyback.js:

function goBack() {
    window.history.back();
}

The index.html file will have this content:

<!DOCTYPE html>
<html>
    <head>
        <title>History Back</title>
    </head>
    
    <body>
        <button onclick="goBack()">Back</button>
        
        <script src="historyback.js"></script>
    </body>
</html>

By now you will have created a button that takes you one page back in the window history. However, the button won’t work if there is no URL in the history.

History Forward

Creating a history forward button is not much different. You have to add another button in index.html and also this code into the historyback.js file:

function goForward(){
    window.history.forward();
}

You’re set to go forward now.

History go

Of course you can also create a button that goes to a specific URL in the history. You would have to use this code snippet to go back 4 pages:

function goTo() {
    window.history.go(-4);
}

The number you put into the go() method is the one who specifies how many pages are you moving back in case you put a negative number in it, or forth in case you put positive numbers in it.

Download the source code

This was an example of history back in Javascript.

Download the source code for this tutorial:

Download
You can download the full source code of this example here: HistoryBack

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button