How to create a Dynamic GO BACK button on a 404 Error Page

Hey friend,welcome back to the site.If its your first time then trust me you have just joined to right crew in web development.

In this simple article, I will take you step by step on how to create a dynamic Back button on the 404 Error Page(Page Not Found) in case you have one. When i say "a dynamic back button" i mean being able to track the previous page the user came from.

If you don't have one(404 Error Page) then first read this article on how to setup or create your custom 404 Error Page for your website.

READ: How to Create a Custom 404 Error Page in HTML.

The logic is very simple, We will be using the window.history object together with the go() method.

The History object provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in).

For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.

The go() method of the History object loads a URL from the history list.

syntax
copy

	history.go(number|URL)

Remember the parameter can either be a number which goes to the last session URL within the specific position or a string. The string must be a partial or full URL, and the function will go to the first URL that matches the string.

Watch the video to see how it's done.

This is the first method on how you can implement a dynamic go back button on your 404 error page.Here we use the inline javascript statement inside the hyper reference attribute (href="").

copy

<a href="javascript:history.go(-1)">go back</a>

Incase you don't want conjest you anchor tag with alot of inline statements,what you need to do is to assign an id to the anchor tag element as shown below.

copy

<a id="backBtn">go back</a>

After assigning an id (forexample:: backBtn) to the element, Then go to the bottom of your page right before the closing body tag (</body>) and create your own custom script tags and insert the code shown below in the middle of the tags.

copy

//select the element and add a click event
document.getElementById('backBtn').addEventListener('click',goBack);

//Function to run when a user clicks the go back button
function goBack(){
  window.location.href="javascript:history.go(-1)";
}


Note: This method will not work if the previous page does not exist in the history list.

Alright friend,thats it for this article but remember they are very many ways to go around this incase this method didn't help you.

collections_bookmark Category :: Javascript
date_range Published :: 4 months ago At: 02:04 PM
person Writer :: Code

YOU MAY LIKE THESE POSTS