Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

history.back() - how to set a default if no history exists

I'm trying to be clever and considerate towards users, but once again, I've run into a "design" issue.

I have a number of pages on a website where I've chosen to remove the default navigation and replace it with a simple "back" button.

The back button functions like this:

href="javascript:history.back()"

I've also "no-indexed" these pages, so in theory all is good.

However, I've one more concern - it's probably never going to happen, but it would be good to know how to resolve it.

Suppose the user bookmarks the page. At present there's no way back, so I was wondering if it was possible to create a default href="/" but override it in some way if there is history. In fact amending the JavaScript function would suffice if I was able to determine if any history existed.

Is this possible? I'm no JS guru, so I might be trying to achieve something that isn't achievable.

like image 520
John Ohara Avatar asked Dec 07 '25 07:12

John Ohara


1 Answers

Set the href to the specific URL, then use javascript to override this behaviour if a history record exists.

<a id="backbtn" href="/specific/url">Back</a>

document.getElementById("backbtn").addEventListener("click", function(){
    if (history.length){
        history.back();
        return false;
    }
});

http://jsfiddle.net/d1gz8ue9/8/

That way your link is still valid without javascript and can be opened in a new window.

like image 130
Curtis Avatar answered Dec 08 '25 19:12

Curtis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!