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.

Add your HTML code to your page. For example this example:

<a href="#" class="back-to-overview" title="Back to overview">Back to overview</a>
Code language: HTML, XML (xml)

And add the following jQuery code example to your code:

/* Check if you're previous page was on the website itself or an extern site */
if (jQuery(".back-to-overview").length) {
    var backToOverviewBtn = jQuery(".back-to-overview");
    var oldUrl = document.referrer;
    var baseUrl = "https://hoolite.be";

    //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 an external website for example Google.")
        backToOverviewBtn.attr("href", baseUrl + "/projects");
    }
}
Code language: JavaScript (javascript)

That’s it!
If you have any questions related to this post, let me know in the comment section below!

You can download the demo files here on GitHub.

Leave your feedback and help us improve 🐢

We hope you found this article helpful! If you have any questions, feedback, or spot any errors, please let us know in the comments. Your input is valuable and helps us improve. If you liked this article, please consider sharing it with others. And if you really enjoyed it, you can show your support by buying us a cup of coffee β˜•οΈ or donating via PayPal πŸ’°.

More free knowledge, because why not?

Your thoughts matter, leave a reply πŸ’¬

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