Payam Shakibafar
Payam Shakibafar

Reputation: 1125

Javascript "Go Back" link which shows the url if there is any

I want to put a "Go Back" link in my website inner pages. the code which I can simply use is :

<script>document.write('<a href="#" onClick="history.go(-1); return:false;"></a>')</script>

but it doesn't show the url of the previous page when someone hovers on it, and also it won't work if there is no previous page(like when you open a link in a new tab). So I need a code which only appears when there is a previous page and also shows the url. I appreciate if anybody knows a good way ..

Upvotes: 1

Views: 996

Answers (3)

Bhavik Shah
Bhavik Shah

Reputation: 2291

document.referrer is my suggestion.

Make a hidden div and place link in that div.

<div id="NavBack">//hide it
    <a>link here</a>
</div>

On document load, check whether something like 'Previous URL' exists or not. If it does then show #NavBack which has the link that can navigate back or just keep it hidden. Refer this

I have updated answer with the patch of code to give you hint.

<div id="NavBack" style="display:none;">
    <a id='test'>link here</a>
</div>
<script type="text/javascript">
if(document.referrer!=''){
    var a = document.getElementById("test");
    a.href=document.referrer;
    document.getElementById("NavBack").style.display='block';
}
</script>

I have used above code and it has worked perfectly. Though, let me make it clear that this is not the standard way, this is just to give you the idea that i want to tell you. Please use jquery instead of javascript and do not give inline CSS in your project.

Upvotes: 2

feeela
feeela

Reputation: 29932

You have to check if there are history entries using window.history.length. If it is greater than zero insert the link.

See also:

https://developer.mozilla.org/en-US/docs/DOM/window.history

https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history

Upvotes: 0

&#201;douard Lopez
&#201;douard Lopez

Reputation: 43401

You can use the history object as describe at the MDN

var h = window.history;
hSize = h.length; // is there any history
h.back();

Also check browser support for these methods.

Upvotes: 0

Related Questions