Simple ‘back to overview’ button with JavaScript

You’re probably here because you need a back button for your website and history.back(); just isn’t enough.

But why use a button when you can use your browsers back button too. Well that’s easy. From A/B testing we noticed that every user has it’s own way to navigate your website. So it isn’t wrong to help them reach there goal.

The script below is still very simple but a bit more advanced then only a back button.

The button will check the URL and will do 2 things.

1: If your previous URL is the same as the base URL of your site, it will use the history.back(); function.

2: If not, for example your visitor came from different website like Google, it will set a fixed URL for example base URL + /projects.

This is a fallback for who ever uses the back button but came from different site. That way they wont go back to the previous website but go to your overview page.

/* Check if you're previous page was on the website itself or an extern site */

var backToOverviewBtn = $j('.back-to-overview');
var oldUrl = document.referrer;

var baseUrl = '';

//console.log('old url:' + $oldUrl);
//console.log('base url:' + $baseUrl);

if (oldUrl.includes(baseUrl)) {
    //console.log('old url contains base url.')
    backToOverviewBtn.attr("href", "javascript:window.history.back();");
} else {
    //console.log('old url is a external website for example Google.')
    backToOverviewBtn.attr("href", baseUrl + "/projects");

That’s it!

You might like this too!

Leave a Reply

Your email address will not be published. Required fields are marked *